Changeset 13975 for issm/trunk/src


Ignore:
Timestamp:
11/16/12 08:10:16 (12 years ago)
Author:
Mathieu Morlighem
Message:

merged trunk-jpl and trunk for revision 13974

Location:
issm/trunk
Files:
57 deleted
855 edited
94 copied

Legend:

Unmodified
Added
Removed
  • issm/trunk

  • issm/trunk/src

  • issm/trunk/src/Makefile.am

    r13395 r13975  
    1 EXTRA_DIST =  perl pro py
    2 SUBDIRS = c modules m
     1EXTRA_DIST =  perl pro
     2SUBDIRS = c m wrappers
     3if ANDROID
     4SUBDIRS += android
     5endif
  • issm/trunk/src/ad/todo

    r13395 r13975  
    5757- make gdb wrapper.
    5858- think about ModelProcessor setup. need to keep track, before we partition, on cpu 0, of the independent declarations.
     59
     60
     61MPI: what's missing that equivalent of MPI.h -> no well defined api. 
     62What's exposed is the internals of it.
     63
     64Wanted to look at changing the way for the matrices and vertices would be implemented.
     65
  • issm/trunk/src/android

    • Property svn:ignore set to
      Makefile.in
      Makefile
  • issm/trunk/src/c/Container/Constraints.cpp

    r12706 r13975  
    4949        /*figure out total number of constraints combining all the cpus (no clones here)*/
    5050        #ifdef _HAVE_MPI_
    51                 MPI_Reduce(&localconstraints,&numberofconstraints,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
    52                 MPI_Bcast(&numberofconstraints,1,MPI_INT,0,MPI_COMM_WORLD);
     51                MPI_Reduce(&localconstraints,&numberofconstraints,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
     52                MPI_Bcast(&numberofconstraints,1,MPI_INT,0,IssmComm::GetComm());
    5353        #else
    5454                numberofconstraints=localconstraints;
    5555        #endif
    56        
    5756
    5857        return numberofconstraints;
  • issm/trunk/src/c/Container/Constraints.h

    r12706 r13975  
    1616class Inputs;
    1717
    18 
    1918class Constraints: public DataSet{
    2019
    2120        public:
    2221
    23                 /*constructors, destructors: {{{*/
     22                /*constructors, destructors*/
    2423                Constraints();
    2524                ~Constraints();
    26                 /*}}}*/
    27                 /*numerics: {{{*/
     25
     26                /*numerics*/
    2827                int   NumberOfConstraints(void);
    29                 /*}}}*/
    3028
    3129};
    3230
    33 
    3431#endif //ifndef _CONSTRAINTS_H_
    35 
  • issm/trunk/src/c/Container/DataSet.cpp

    r13395 r13975  
    3030/*FUNCTION DataSet::DataSet(){{{*/
    3131DataSet::DataSet(){
    32        
     32
    3333        sorted=0;
    3434        sorted_ids=NULL;
     
    4040DataSet::DataSet(int dataset_enum){
    4141        enum_type=dataset_enum;
    42        
     42
    4343        sorted=0;
    4444        sorted_ids=NULL;
     
    5050DataSet*   DataSet::Copy(void){
    5151
    52         DataSet* copy=NULL;
    5352        vector<Object*>::iterator object;
    5453        Object* object_copy=NULL;
    5554
    56         copy=new DataSet(enum_type);
     55        DataSet* copy=new DataSet(enum_type);
    5756
    5857        copy->sorted=sorted;
     
    130129void DataSet::DeepEcho(){
    131130
    132 
    133131        vector<Object*>::iterator object;
    134132
     
    191189        int id_offset;
    192190        int offset;
    193         int i;
    194191
    195192        _assert_(this);
     
    216213        /*vector of objects is already sorted, just allocate the sorted ids and their
    217214         * offsets:*/
    218         int i;
    219 
    220215        if(objects.size()){
    221216
     
    229224
    230225                /*Build id_offsets and sorted_ids*/
    231                 for(i=0;i<objects.size();i++){
     226                for(int i=0;i<objects.size();i++){
    232227                        id_offsets[i]=i;
    233228                        sorted_ids[i]=objects[i]->Id();
  • issm/trunk/src/c/Container/DataSet.h

    r13395 r13975  
    2323
    2424class DataSet{
    25        
     25
    2626        public:
    27                
     27
    2828                /*internals: */
    2929                std::vector<Object*> objects;
    30                
     30
    3131                /*type of dataset: */
    3232                int             enum_type;
    33                
     33
    3434                /*sorting: */
    3535                int             sorted;
     
    3838                int*            id_offsets;
    3939
    40                 /*constructors, destructors: {{{*/
     40                /*constructors, destructors*/
    4141                DataSet();
    4242                DataSet(int enum_type);
    4343                ~DataSet();
    44                 /*}}}*/
    45                 /*management: {{{*/
    46                 int   GetEnum();
    47                 int   GetEnum(int offset);
    48                 void  Echo();
    49                 void  DeepEcho();
    50                 int   AddObject(Object* object);
    51                 int   DeleteObject(int id);
    52                 int   Size();
    53                 void  clear();
    54                 Object* GetObjectByOffset(int offset);
    55                 Object* GetObjectById(int* poffset,int eid);
    56                 void  Presort();
    57                 void  SetSorting(int* in_sorted_ids,int* in_id_offsets);
    58                 void  Sort();
    59                 DataSet* Copy(void);
    60                 int   DeleteObject(Object* object);
    61                 Results* SpawnTriaResults(int* indices);
    62                 /*}}}*/
     44
     45                /*management*/
     46                int      GetEnum();
     47                int      GetEnum(int offset);
     48                void     Echo();
     49                void     DeepEcho();
     50                int      AddObject(Object *object);
     51                int      DeleteObject(int id);
     52                int      Size();
     53                void     clear();
     54                Object  *GetObjectByOffset(int  offset);
     55                Object  *GetObjectById(int *poffset,int eid);
     56                void     Presort();
     57                void     SetSorting(int *in_sorted_ids,int*in_id_offsets);
     58                void     Sort();
     59                DataSet *Copy(void);
     60                int      DeleteObject(Object *object);
     61                Results *SpawnTriaResults(int *indices);
    6362
    6463};
  • issm/trunk/src/c/Container/Elements.cpp

    r13395 r13975  
    4646        for ( object=objects.begin() ; object < objects.end(); object++ ){
    4747
    48                 element=(Element*)(*object);
     48                element=dynamic_cast<Element*>((*object));
    4949                element->Configure(elements,loads,nodes,materials,parameters);
    5050
     
    5858        //Process results to be output in the correct units
    5959        for(int i=0;i<this->Size();i++){
    60                 Element* element=(Element*)this->GetObjectByOffset(i);
     60                Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
    6161                element->ProcessResultsUnits();
    6262        }
     
    6565/*FUNCTION Elements::DeleteResults{{{*/
    6666void Elements::DeleteResults(void){
    67        
     67
    6868        for (int i=0;i<this->Size();i++){
    69                 Element* element=(Element*)this->GetObjectByOffset(i);
     69                Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
    7070                element->DeleteResults();
    7171        }
     
    108108         * We will use the Patch object, which will store all of the information needed, and will be able
    109109         * to output itself to disk on its own. See object/Patch.h for format of this object.*/
    110        
     110
    111111        /*First, determine maximum number of vertices, nodes, and number of results: */
    112112        numrows=0;
     
    116116        for(i=0;i<this->Size();i++){
    117117
    118                 Element* element=(Element*)this->GetObjectByOffset(i);
     118                Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
    119119                element->PatchSize(&element_numrows,&element_numvertices,&element_numnodes);
    120120
     
    126126        /*Synchronize across cluster, so as to not end up with different sizes for each patch on each cpu: */
    127127        #ifdef _HAVE_MPI_
    128         MPI_Reduce (&numvertices,&max_numvertices,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD );
    129         MPI_Bcast(&max_numvertices,1,MPI_INT,0,MPI_COMM_WORLD);
     128        MPI_Reduce (&numvertices,&max_numvertices,1,MPI_INT,MPI_MAX,0,IssmComm::GetComm() );
     129        MPI_Bcast(&max_numvertices,1,MPI_INT,0,IssmComm::GetComm());
    130130        numvertices=max_numvertices;
    131131
    132         MPI_Reduce (&numnodes,&max_numnodes,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD );
    133         MPI_Bcast(&max_numnodes,1,MPI_INT,0,MPI_COMM_WORLD);
     132        MPI_Reduce (&numnodes,&max_numnodes,1,MPI_INT,MPI_MAX,0,IssmComm::GetComm() );
     133        MPI_Bcast(&max_numnodes,1,MPI_INT,0,IssmComm::GetComm());
    134134        numnodes=max_numnodes;
    135135        #endif
     
    141141        count=0;
    142142        for(i=0;i<this->Size();i++){
    143                 Element* element=(Element*)this->GetObjectByOffset(i);
     143                Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
    144144                element->PatchFill(&count,patch);
    145145        }
     
    156156        for ( object=objects.begin() ; object < objects.end(); object++ ){
    157157
    158                 element=(Element*)(*object);
     158                element=dynamic_cast<Element*>((*object));
    159159                element->SetCurrentConfiguration(elements,loads,nodes,materials,parameters);
    160160
     
    166166void Elements::ToResults(Results* results,Parameters* parameters){
    167167
    168         int i;
    169        
    170         extern int my_rank;
    171         extern int num_procs;
    172 
    173         Patch  *patch        = NULL;
    174         int    *resultsenums = NULL;
    175         int    *resultssizes  = NULL;
    176         int    *resultssteps  = NULL;
    177         IssmDouble *resultstimes = NULL;
    178         IssmDouble *vector_serial= NULL;
    179         Vector<IssmDouble>*     vector       = NULL;
    180         bool   io_gather;
    181         bool   results_as_patches;
    182         int    numberofvertices,numberofelements;
    183         int    numberofresults,vectorsize;
    184         int    rank;
    185         int    minrank;
     168        int my_rank;
     169        int num_procs;
     170
     171        Patch               *patch              = NULL;
     172        int                 *resultsenums       = NULL;
     173        int                 *resultssizes       = NULL;
     174        int                 *resultssteps       = NULL;
     175        IssmDouble          *resultstimes       = NULL;
     176        IssmDouble          *vector_serial      = NULL;
     177        Vector<IssmDouble> *vector = NULL;
     178        bool                io_gather;
     179        bool                results_as_patches;
     180        int                 numberofvertices     ,numberofelements;
     181        int                 numberofresults      ,vectorsize;
     182        int                 rank;
     183        int                 minrank;
     184
     185        /*recover my_rank:*/
     186        my_rank=IssmComm::GetRank();
     187        num_procs=IssmComm::GetSize();
    186188
    187189        /*Recover parameters: */
     
    198200                if(this->Size()) rank=my_rank;
    199201                else rank=num_procs;
    200                 MPI_Allreduce (&rank,&minrank,1,MPI_INT,MPI_MIN,MPI_COMM_WORLD);
     202                MPI_Allreduce (&rank,&minrank,1,MPI_INT,MPI_MIN,IssmComm::GetComm());
    201203                #else
    202204                minrank=my_rank;
     
    206208                if(my_rank==minrank){
    207209                        if(this->Size()==0) _error_("Cannot write results because there is no element??");
    208                         Element* element=(Element*)this->GetObjectByOffset(0);
     210                        Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(0));
    209211                        element->ListResultsInfo(&resultsenums,&resultssizes,&resultstimes,&resultssteps,&numberofresults);
    210212                }
    211213                #ifdef _HAVE_MPI_
    212                 MPI_Bcast(&numberofresults,1,MPI_DOUBLE,minrank,MPI_COMM_WORLD);
     214                MPI_Bcast(&numberofresults,1,MPI_DOUBLE,minrank,IssmComm::GetComm());
    213215                #endif
    214216
     
    222224                        resultssteps=xNew<int>(numberofresults);
    223225                }
    224                 MPI_Bcast(resultsenums,numberofresults,MPI_INT,minrank,MPI_COMM_WORLD);
    225                 MPI_Bcast(resultssizes,numberofresults,MPI_INT,minrank,MPI_COMM_WORLD);
    226                 MPI_Bcast(resultstimes,numberofresults,MPI_DOUBLE,minrank,MPI_COMM_WORLD);
    227                 MPI_Bcast(resultssteps,numberofresults,MPI_INT,minrank,MPI_COMM_WORLD);
     226                MPI_Bcast(resultsenums,numberofresults,MPI_INT,minrank,IssmComm::GetComm());
     227                MPI_Bcast(resultssizes,numberofresults,MPI_INT,minrank,IssmComm::GetComm());
     228                MPI_Bcast(resultstimes,numberofresults,MPI_DOUBLE,minrank,IssmComm::GetComm());
     229                MPI_Bcast(resultssteps,numberofresults,MPI_INT,minrank,IssmComm::GetComm());
    228230                #endif
    229231
     
    238240
    239241                        for(int j=0;j<this->Size();j++){
    240                                 Element* element=(Element*)this->GetObjectByOffset(j);
     242                                Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(j));
    241243                                element->GetVectorFromResults(vector,i,resultsenums[i],resultssizes[i]);
    242244                        }
     
    292294}
    293295/*}}}*/
     296/*FUNCTION Elements::MaxNumNodes{{{*/
     297int Elements::MaxNumNodes(void){
     298
     299        int max=0;
     300        int allmax;
     301        int numnodes=0;
     302
     303        /*Now go through all elements, and get how many nodes they own, unless they are clone nodes: */
     304        for(int i=0;i<this->Size();i++){
     305
     306                Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
     307                numnodes=element->GetNumberOfNodes();
     308                if(numnodes>max)max=numnodes;
     309        }
     310
     311        /*Grab max of all cpus: */
     312        #ifdef _HAVE_MPI_
     313        MPI_Allreduce((void*)&max,(void*)&allmax,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
     314        max=allmax;
     315        #endif
     316
     317        return max;
     318}
     319/*}}}*/
    294320/*FUNCTION Elements::NumberOfElements{{{*/
    295321int Elements::NumberOfElements(void){
    296322
    297         int local_nelem=0;
     323        int local_nelem;
    298324        int numberofelements;
    299325
    300326        local_nelem=this->Size();
    301327        #ifdef _HAVE_MPI_
    302         MPI_Allreduce ( (void*)&local_nelem,(void*)&numberofelements,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
     328        MPI_Allreduce ( (void*)&local_nelem,(void*)&numberofelements,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
    303329        #else
    304330        numberofelements=local_nelem;
     
    312338
    313339        for(int i=0;i<this->Size();i++){
    314                 Element* element=(Element*)this->GetObjectByOffset(i);
     340                Element* element=dynamic_cast<Element*>(this->GetObjectByOffset(i));
    315341                element->InputDuplicate(input_enum,output_enum);
    316342        }
  • issm/trunk/src/c/Container/Elements.h

    r12706 r13975  
    2020        public:
    2121
    22                 /*constructors, destructors: {{{*/
     22                /*constructors, destructors*/
    2323                Elements();
    2424                ~Elements();
    25                 /*}}}*/
    26                 /*numerics: {{{*/
    27                 void Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
    28                 void DeleteResults(void);
    29                 void ProcessResultsUnits(void);
    30                 void SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
    31                 void ToResults(Results* results,Parameters* parameters);
     25
     26                /*numerics*/
     27                void   Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
     28                void   DeleteResults(void);
     29                int    MaxNumNodes(void);
     30                void   ProcessResultsUnits(void);
     31                void   SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
     32                void   ToResults(Results* results,Parameters* parameters);
    3233                Patch* ResultsToPatch(void);
    33                 int   NumberOfElements(void);
    34                 void InputDuplicate(int input_enum,int output_enum);
    35                 /*}}}*/
     34                int    NumberOfElements(void);
     35                void   InputDuplicate(int input_enum,int output_enum);
    3636
    3737};
  • issm/trunk/src/c/Container/Inputs.cpp

    r13395 r13975  
    4747        for ( object=objects.begin() ; object < objects.end(); object++ ){
    4848
    49                 input=(Input*)(*object);
     49                input=dynamic_cast<Input*>(*object);
    5050                if (input->InstanceEnum()==enum_type){
    5151                        found=true;
     
    7575        for ( object=objects.begin() ; object < objects.end(); object++ ){
    7676
    77                 input=(Input*)(*object);
     77                input=dynamic_cast<Input*>(*object);
    7878                if (input->InstanceEnum()==enum_type){
    7979                        found=true;
     
    103103        for ( object=objects.begin() ; object < objects.end(); object++ ){
    104104
    105                 input=(Input*)(*object);
     105                input=dynamic_cast<Input*>(*object);
    106106                if (input->InstanceEnum()==enum_type){
    107107                        found=true;
     
    131131        for ( object=objects.begin() ; object < objects.end(); object++ ){
    132132
    133                 input=(Input*)(*object);
     133                input=dynamic_cast<Input*>(*object);
    134134                if (input->InstanceEnum()==enum_type){
    135135                        found=true;
     
    163163        for ( object=objects.begin() ; object < objects.end(); object++ ){
    164164
    165                 input=(Input*)(*object);
     165                input=dynamic_cast<Input*>(*object);
    166166
    167167                if (input->InstanceEnum()==in_input->InstanceEnum()){
     
    185185        /*Delete existing input of newenumtype if it exists*/
    186186        for ( object=objects.begin() ; object < objects.end(); object++ ){
    187                 input=(Input*)(*object);
     187                input=dynamic_cast<Input*>(*object);
    188188
    189189                if (input->InstanceEnum()==newenumtype){
     
    196196        for ( object=objects.begin() ; object < objects.end(); object++ ){
    197197
    198                 input=(Input*)(*object);
     198                input=dynamic_cast<Input*>(*object);
    199199
    200200                if (input->InstanceEnum()==oldenumtype){
     
    207207/*FUNCTION Inputs::ConstrainMin{{{*/
    208208void  Inputs::ConstrainMin(int constrain_enum, IssmDouble minimum){
    209            
    210         Input* constrain_input=NULL;
     209
    211210        /*Find x and y inputs: */
    212         constrain_input=(Input*)this->GetInput(constrain_enum);
     211        Input* constrain_input=dynamic_cast<Input*>(this->GetInput(constrain_enum));
    213212
    214213        /*some checks: */
     
    226225
    227226        /*Get input*/
    228         Input* input=(Input*)this->GetInput(enumtype);
     227        Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
    229228
    230229        /*Apply ContrainMin: */
     
    247246
    248247        /*Get input*/
    249         Input* input=(Input*)this->GetInput(enumtype);
     248        Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
    250249
    251250        /*Apply ContrainMin: */
     
    268267
    269268        /*Get input*/
    270         Input* input=(Input*)this->GetInput(enumtype);
     269        Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
    271270
    272271        /*Apply ContrainMin: */
     
    289288
    290289        /*Get input*/
    291         Input* input=(Input*)this->GetInput(enumtype);
     290        Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
    292291
    293292        /*Apply ContrainMin: */
     
    310309
    311310        /*Get input*/
    312         Input* input=(Input*)this->GetInput(enumtype);
     311        Input* input=dynamic_cast<Input*>(this->GetInput(enumtype));
    313312
    314313        /*Apply ContrainMin: */
     
    332331        for ( object=objects.begin() ; object < objects.end(); object++ ){
    333332
    334                 input=(Input*)(*object);
     333                input=dynamic_cast<Input*>(*object);
    335334
    336335                if (input->InstanceEnum()==enum_name){
     
    349348        for ( object=objects.begin() ; object < objects.end(); object++ ){
    350349
    351                 input=(Input*)(*object);
     350                input=dynamic_cast<Input*>(*object);
    352351
    353352                if (input->InstanceEnum()==enum_type){
     
    364363void  Inputs::DuplicateInput(int original_enum,int new_enum){
    365364
    366         Input* original=NULL;
    367         Input* copy=NULL;
    368 
    369365        /*Make a copy of the original input: */
    370         original=(Input*)this->GetInput(original_enum);
     366        Input* original=dynamic_cast<Input*>(this->GetInput(original_enum));
    371367        if(!original)_error_("could not find input with enum: " << EnumToStringx(original_enum));
    372         copy=(Input*)original->copy();
     368        Input* copy=dynamic_cast<Input*>(original->copy());
    373369
    374370        /*Change copy enum to reinitialized_enum: */
     
    376372
    377373        /*Add copy into inputs, it will wipe off the one already there: */
    378         this->AddInput((Input*)copy);
     374        this->AddInput(dynamic_cast<Input*>(copy));
    379375}
    380376/*}}}*/
     
    394390
    395391                /*Create new input*/
    396                 inputin=(Input*)(*object);
     392                inputin=dynamic_cast<Input*>(*object);
    397393                inputout=inputin->SpawnTriaInput(indices);
    398394
     
    407403/*FUNCTION Inputs::AXPY{{{*/
    408404void  Inputs::AXPY(int MeshYEnum, IssmDouble scalar, int MeshXEnum){
    409            
    410         Input* xinput=NULL;
    411         Input* yinput=NULL;
    412405
    413406        /*Find x and y inputs: */
    414         xinput=(Input*)this->GetInput(MeshXEnum);
    415         yinput=(Input*)this->GetInput(MeshYEnum);
     407        Input* xinput=dynamic_cast<Input*>(this->GetInput(MeshXEnum));
     408        Input* yinput=dynamic_cast<Input*>(this->GetInput(MeshYEnum));
    416409
    417410        /*some checks: */
     
    431424        for ( object=objects.begin() ; object < objects.end(); object++ ){
    432425
    433                 input=(Input*)(*object);
     426                input=dynamic_cast<Input*>(*object);
    434427                input->Configure(parameters);
    435428
  • issm/trunk/src/c/Container/Inputs.h

    r12706 r13975  
    2323        public:
    2424
    25                 /*constructors, destructors: {{{*/
     25                /*constructors, destructors*/
    2626                Inputs();
    2727                ~Inputs();
    2828
    29                 /*}}}*/
    30                 /*numerics: {{{*/
    31                 int     AddInput(Input* in_input);
    32                 void    ChangeEnum(int enumtype,int new_enumtype);
    33                 void    ConstrainMin(int constrain_enum, IssmDouble minimum);
    34                 int     DeleteInput(int enum_type);
    35                 void    DuplicateInput(int original_enum,int new_enum);
    36                 Input*  GetInput(int enum_name);
    37                 Inputs* SpawnTriaInputs(int* indices);
    38                 void    AXPY(int MeshYEnum, IssmDouble scalar, int MeshXEnum);
     29                /*numerics*/
     30                int        AddInput(Input* in_input);
     31                void       ChangeEnum(int enumtype,int new_enumtype);
     32                void       ConstrainMin(int constrain_enum, IssmDouble minimum);
     33                int        DeleteInput(int enum_type);
     34                void       DuplicateInput(int original_enum,int new_enum);
     35                Input*     GetInput(int enum_name);
     36                Inputs*    SpawnTriaInputs(int* indices);
     37                void       AXPY(int MeshYEnum, IssmDouble scalar, int MeshXEnum);
    3938                IssmDouble  InfinityNorm(int enumtype);
    4039                IssmDouble  Max(int enumtype);
     
    4241                IssmDouble  Min(int enumtype);
    4342                IssmDouble  MinAbs(int enumtype);
    44                
    4543                void GetInputAverage(IssmDouble* pvalue, int enum_type);
    4644                void GetInputValue(bool* pvalue,int enum_type);
    4745                void GetInputValue(int* pvalue,int enum_type);
    4846                void GetInputValue(IssmDouble* pvalue,int enum_type);
    49 
    5047                void Configure(Parameters* parameters);
    51                 /*}}}*/
    5248
    5349};
  • issm/trunk/src/c/Container/Loads.cpp

    r12706 r13975  
    4646        for ( object=objects.begin() ; object < objects.end(); object++ ){
    4747
    48                 load=(Load*)(*object);
     48                load=dynamic_cast<Load*>(*object);
    4949                load->Configure(elements,loads,nodes,vertices,materials,parameters);
    5050
     
    5353}
    5454/*}}}*/
    55 /*FUNCTION Loads::NumberOfLoads{{{*/
     55/*FUNCTION Loads::IsPenalty{{{*/
     56bool Loads::IsPenalty(int analysis_type){
     57
     58        int ispenalty=0;
     59        int allispenalty=0;
     60
     61        /*Now go through all loads, and get how many nodes they own, unless they are clone nodes: */
     62        for(int i=0;i<this->Size();i++){
     63
     64                Load* load=dynamic_cast<Load*>(this->GetObjectByOffset(i));
     65                if (load->InAnalysis(analysis_type)){
     66                        if(load->IsPenalty()) ispenalty++;
     67                }
     68        }
     69
     70        /*Grab sum of all cpus: */
     71#ifdef _HAVE_MPI_
     72        MPI_Allreduce((void*)&ispenalty,(void*)&allispenalty,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
     73        ispenalty=allispenalty;
     74#endif
     75
     76        if(ispenalty)
     77         return true;
     78        else
     79         return false;
     80}
     81/*}}}*/
     82/*FUNCTION Loads::MaxNumNodes{{{*/
     83int Loads::MaxNumNodes(int analysis_type){
     84
     85        int max=0;
     86        int allmax;
     87        int numnodes=0;
     88
     89        /*Now go through all loads, and get how many nodes they own, unless they are clone nodes: */
     90        for(int i=0;i<this->Size();i++){
     91
     92                Load* load=dynamic_cast<Load*>(this->GetObjectByOffset(i));
     93                if (load->InAnalysis(analysis_type)){
     94                        numnodes=load->GetNumberOfNodes();
     95                        if(numnodes>max)max=numnodes;
     96                }
     97        }
     98
     99        /*Grab max of all cpus: */
     100#ifdef _HAVE_MPI_
     101        MPI_Allreduce((void*)&max,(void*)&allmax,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
     102        max=allmax;
     103#endif
     104
     105        return max;
     106}
     107/*}}}*/
     108/*FUNCTION Loads::NumberOfLoads(){{{*/
    56109int Loads::NumberOfLoads(void){
    57110
    58         int localloads=0;
    59         int numberofloads=0;
     111        int localloads;
     112        int numberofloads;
    60113
    61114        /*Get number of local loads*/
     
    64117        /*figure out total number of loads combining all the cpus (no clones here)*/
    65118        #ifdef _HAVE_MPI_
    66         MPI_Reduce(&localloads,&numberofloads,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
    67         MPI_Bcast(&numberofloads,1,MPI_INT,0,MPI_COMM_WORLD);
     119        MPI_Reduce(&localloads,&numberofloads,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
     120        MPI_Bcast(&numberofloads,1,MPI_INT,0,IssmComm::GetComm());
    68121        #else
    69122        numberofloads=localloads;
    70123        #endif
    71124
     125        return numberofloads;
     126}
     127/*}}}*/
     128/*FUNCTION Loads::NumberOfLoads(int analysis){{{*/
     129int Loads::NumberOfLoads(int analysis_type){
     130
     131        int localloads = 0;
     132        int numberofloads;
     133
     134        /*Get number of local loads*/
     135        for(int i=0;i<this->Size();i++){
     136
     137                Load* load=dynamic_cast<Load*>(this->GetObjectByOffset(i));
     138
     139                /*Check that this load corresponds to our analysis currently being carried out: */
     140                if (load->InAnalysis(analysis_type)) localloads++;
     141        }
     142
     143        /*figure out total number of loads combining all the cpus (no clones here)*/
     144#ifdef _HAVE_MPI_
     145        MPI_Reduce(&localloads,&numberofloads,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
     146        MPI_Bcast(&numberofloads,1,MPI_INT,0,IssmComm::GetComm());
     147#else
     148        numberofloads=localloads;
     149#endif
    72150
    73151        return numberofloads;
     152}
     153/*}}}*/
     154/*FUNCTION Loads::Size(){{{*/
     155int Loads::Size(void){
     156
     157        return this->DataSet::Size();
     158}
     159/*}}}*/
     160/*FUNCTION Loads::Size(int analysis){{{*/
     161int Loads::Size(int analysis_type){
     162
     163        int localloads = 0;
     164
     165        /*Get number of local loads*/
     166        for(int i=0;i<this->Size();i++){
     167
     168                Load* load=dynamic_cast<Load*>(this->GetObjectByOffset(i));
     169
     170                /*Check that this load corresponds to our analysis currently being carried out: */
     171                if (load->InAnalysis(analysis_type)) localloads++;
     172        }
     173
     174        return localloads;
    74175}
    75176/*}}}*/
     
    82183        for ( object=objects.begin() ; object < objects.end(); object++ ){
    83184
    84                 load=(Load*)(*object);
     185                load=dynamic_cast<Load*>(*object);
    85186                load->SetCurrentConfiguration(elements,loads,nodes,vertices,materials,parameters);
    86187
  • issm/trunk/src/c/Container/Loads.h

    r12706 r13975  
    2020        public:
    2121
    22                 /*constructors, destructors: {{{*/
     22                /*constructors, destructors*/
    2323                Loads();
    2424                ~Loads();
    25                 /*}}}*/
    26                 /*numerics: {{{*/
     25
     26                /*numerics*/
    2727                void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
     28                bool  IsPenalty(int analysis);
     29                int   MaxNumNodes(int analysis);
    2830                int   NumberOfLoads(void);
     31                int   NumberOfLoads(int analysis);
    2932                void  SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
    30                 /*}}}*/
     33                int   Size(int analysis);
     34                int   Size(void);
    3135
    3236};
  • issm/trunk/src/c/Container/Materials.cpp

    r12706 r13975  
    4646        for ( object=objects.begin() ; object < objects.end(); object++ ){
    4747
    48                 material=(Material*)(*object);
     48                material=dynamic_cast<Material*>(*object);
    4949                material->Configure(elements);
    5050
  • issm/trunk/src/c/Container/Materials.h

    r12706 r13975  
    1919        public:
    2020
    21                 /*constructors, destructors: {{{*/
     21                /*constructors, destructors*/
    2222                Materials();
    2323                ~Materials();
    24                 /*}}}*/
    25                 /*numerics: {{{*/
     24
     25                /*numerics*/
    2626                void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
    27                 /*}}}*/
    2827
    2928};
  • issm/trunk/src/c/Container/Nodes.cpp

    r12706 r13975  
    4646        for ( object=objects.begin() ; object < objects.end(); object++ ){
    4747
    48                 node=(Node*)(*object);
     48                node=dynamic_cast<Node*>(*object);
    4949                node->Configure(nodes,vertices);
    5050
     
    5555/*FUNCTION Nodes::DistributeDofs{{{*/
    5656void  Nodes::DistributeDofs(int analysis_type,int setenum){
    57 
    58         extern int num_procs;
    59         extern int my_rank;
    6057
    6158        int  i;
     
    6764        int  numnodes=0;
    6865
     66        /*recover my_rank:*/
     67        int my_rank   = IssmComm::GetRank();
     68        int num_procs = IssmComm::GetSize();
     69
    6970        /*some check: */
    7071        _assert_(setenum==GsetEnum || setenum==FsetEnum || setenum==SsetEnum);
     
    7273        /*Go through objects, and distribute dofs locally, from 0 to numberofdofsperobject*/
    7374        for (i=0;i<this->Size();i++){
    74                 Node* node=(Node*)this->GetObjectByOffset(i);
     75                Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
    7576
    7677                /*Check that this node corresponds to our analysis currently being carried out: */
     
    8687        alldofcount=xNew<int>(num_procs);
    8788        #ifdef _HAVE_MPI_
    88         MPI_Gather(&dofcount,1,MPI_INT,alldofcount,1,MPI_INT,0,MPI_COMM_WORLD);
    89         MPI_Bcast(alldofcount,num_procs,MPI_INT,0,MPI_COMM_WORLD);
     89        MPI_Gather(&dofcount,1,MPI_INT,alldofcount,1,MPI_INT,0,IssmComm::GetComm());
     90        MPI_Bcast(alldofcount,num_procs,MPI_INT,0,IssmComm::GetComm());
    9091        #else
    9192        alldofcount[0]=dofcount;
     
    9495        /* Every cpu should start its own dof count at the end of the dofcount from cpu-1*/
    9596        dofcount=0;
    96         if(my_rank!=0){
    97                 for(i=0;i<my_rank;i++){
    98                         dofcount+=alldofcount[i];
    99                 }
     97        for(i=0;i<my_rank;i++){
     98                dofcount+=alldofcount[i];
    10099        }
    101100        for (i=0;i<this->Size();i++){
    102101                /*Check that this node corresponds to our analysis currently being carried out: */
    103                 Node* node=(Node*)this->GetObjectByOffset(i);
     102                Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
    104103                if (node->InAnalysis(analysis_type)){
    105104                        node->OffsetDofs(dofcount,setenum);
     
    118117
    119118        for (i=0;i<this->Size();i++){
    120                 Node* node=(Node*)this->GetObjectByOffset(i);
     119                Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
    121120                if (node->InAnalysis(analysis_type)){
    122121                        node->ShowTrueDofs(truedofs,maxdofspernode,setenum);//give maxdofspernode, column size, so that nodes can index into truedofs
     
    125124
    126125        #ifdef _HAVE_MPI_
    127         MPI_Allreduce((void*)truedofs,(void*)alltruedofs,numnodes*maxdofspernode,MPI_INT,MPI_MAX,MPI_COMM_WORLD);
     126        MPI_Allreduce((void*)truedofs,(void*)alltruedofs,numnodes*maxdofspernode,MPI_INT,MPI_MAX,IssmComm::GetComm());
    128127        #else
    129128        for(i=0;i<numnodes*maxdofspernode;i++)alltruedofs[i]=truedofs[i];
     
    132131        /* Now every cpu knows the true dofs of everyone else that is not a clone*/
    133132        for (i=0;i<this->Size();i++){
    134                 Node* node=(Node*)this->GetObjectByOffset(i);
     133                Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
    135134                if (node->InAnalysis(analysis_type)){
    136135                        node->UpdateCloneDofs(alltruedofs,maxdofspernode,setenum);
     
    148147
    149148        int i;
    150         extern int num_procs;
    151 
    152         int* ranks=NULL;
    153         int* minranks=NULL;
    154         int  numnodes;
     149        int num_procs;
     150        int numnodes;
     151
     152        /*recover num_procs: */
     153        num_procs=IssmComm::GetSize();
    155154
    156155        /*Figure out number of nodes for this analysis: */
     
    158157
    159158        /*Allocate ranks: */
    160         ranks=xNew<int>(numnodes);
    161         minranks=xNew<int>(numnodes);
    162 
     159        int* ranks    = xNew<int>(numnodes);
     160        int* minranks = xNew<int>(numnodes);
    163161        for(i=0;i<numnodes;i++)ranks[i]=num_procs; //no cpu can have rank num_procs. This is the maximum limit.
    164162
     
    171169         * order of cpu rank. This is also why we initialized this array to num_procs.*/
    172170        #ifdef _HAVE_MPI_
    173         MPI_Allreduce ( (void*)ranks,(void*)minranks,numnodes,MPI_INT,MPI_MIN,MPI_COMM_WORLD);
     171        MPI_Allreduce((void*)ranks,(void*)minranks,numnodes,MPI_INT,MPI_MIN,IssmComm::GetComm());
    174172        #else
    175173        for(i=0;i<numnodes;i++)minranks[i]=ranks[i];
     
    179177        for(i=0;i<this->Size();i++){
    180178
    181                 Node* node=(Node*)this->GetObjectByOffset(i);
     179                Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
    182180
    183181                /*Check that this node corresponds to our analysis currently being carried out: */
     
    199197
    200198        int i;
    201         int   max=0;
    202         int   allmax;
    203         int   numdofs=0;
     199        int max=0;
     200        int allmax;
     201        int numdofs=0;
    204202
    205203        /*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
    206204        for(i=0;i<this->Size();i++){
    207205
    208                 Node* node=(Node*)this->GetObjectByOffset(i);
     206                Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
    209207
    210208                /*Check that this node corresponds to our analysis currently being carried out: */
     
    212210
    213211                        numdofs=node->GetNumberOfDofs(NoneApproximationEnum,setenum);
    214                         if (numdofs>max)max=numdofs;
     212                        if(numdofs>max)max=numdofs;
    215213                }
    216214        }
     
    218216        /*Grab max of all cpus: */
    219217        #ifdef _HAVE_MPI_
    220         MPI_Allreduce ( (void*)&max,(void*)&allmax,1,MPI_INT,MPI_MAX,MPI_COMM_WORLD);
     218        MPI_Allreduce((void*)&max,(void*)&allmax,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
    221219        max=allmax;
    222220        #endif
     
    228226int   Nodes::NumberOfDofs(int analysis_type,int setenum){
    229227
    230         int i;
    231        
     228        int   allnumdofs;
     229
     230        /*Get number of dofs on current cpu (excluding clones)*/
     231        int numdofs=this->NumberOfDofsLocal(analysis_type,setenum);
     232
     233        /*Gather from all cpus: */
     234        #ifdef _HAVE_MPI_
     235        MPI_Allreduce ( (void*)&numdofs,(void*)&allnumdofs,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
     236        #else
     237        allnumdofs=numdofs;
     238        #endif
     239        return allnumdofs;
     240}
     241/*}}}*/
     242/*FUNCTION Nodes::NumberOfDofsLocal{{{*/
     243int   Nodes::NumberOfDofsLocal(int analysis_type,int setenum){
     244
    232245        int   numdofs=0;
    233         int   allnumdofs;
    234246
    235247        /*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
    236         for(i=0;i<this->Size();i++){
    237 
    238                 Node* node=(Node*)this->GetObjectByOffset(i);
     248        for(int i=0;i<this->Size();i++){
     249
     250                Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
    239251
    240252                /*Check that this node corresponds to our analysis currently being carried out: */
     
    243255                        /*Ok, this object is a node, ask it to plug values into partition: */
    244256                        if (!node->IsClone()){
    245 
    246257                                numdofs+=node->GetNumberOfDofs(NoneApproximationEnum,setenum);
    247 
    248258                        }
    249259                }
    250260        }
    251261
    252         /*Gather from all cpus: */
    253         #ifdef _HAVE_MPI_
    254         MPI_Allreduce ( (void*)&numdofs,(void*)&allnumdofs,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
    255         #else
    256         allnumdofs=numdofs;
    257         #endif
    258         return allnumdofs;
     262        return numdofs;
    259263}
    260264/*}}}*/
     
    264268        /*Careful! only use once all clones have been setup for all nodes!: */
    265269
    266         int i;
    267        
    268         int   numnodes=0;
    269         int   allnumnodes=0;
     270        int numnodes=0;
     271        int allnumnodes=0;
    270272
    271273        /*Now go through all nodes, and get how many dofs they own, unless they are clone nodes: */
    272         for(i=0;i<this->Size();i++){
    273                 Node* node=(Node*)this->GetObjectByOffset(i);
     274        for(int i=0;i<this->Size();i++){
     275                Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
    274276
    275277                /*Ok, this object is a node, ask it to plug values into partition: */
     
    279281        /*Gather from all cpus: */
    280282        #ifdef _HAVE_MPI_
    281         MPI_Allreduce ( (void*)&numnodes,(void*)&allnumnodes,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
     283        MPI_Allreduce ( (void*)&numnodes,(void*)&allnumnodes,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
    282284        #else
    283285        allnumnodes=numnodes;
     
    298300        for(i=0;i<this->Size();i++){
    299301
    300                 Node* node=(Node*)this->GetObjectByOffset(i);
     302                Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
    301303
    302304                /*Check that this node corresponds to our analysis currently being carried out: */
     
    309311
    310312        #ifdef _HAVE_MPI_
    311         MPI_Reduce (&max_sid,&node_max_sid,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD );
    312         MPI_Bcast(&node_max_sid,1,MPI_INT,0,MPI_COMM_WORLD);
     313        MPI_Reduce (&max_sid,&node_max_sid,1,MPI_INT,MPI_MAX,0,IssmComm::GetComm() );
     314        MPI_Bcast(&node_max_sid,1,MPI_INT,0,IssmComm::GetComm());
    313315        max_sid=node_max_sid;
    314316        #endif
    315317
    316         if(max_sid==1){
    317                 return 0;
    318         }
    319         else{
    320                 /*sid starts at 0*/
    321                 max_sid++;
    322        
    323                 /*return*/
    324                 return max_sid;
    325         }
     318        /*sid starts at 0*/
     319        max_sid++;
     320
     321        /*return*/
     322        return max_sid;
    326323}
    327324/*}}}*/
     
    329326void   Nodes::Ranks(int* ranks,int analysis_type){
    330327
     328        int my_rank;
     329        int sid;
     330
     331        /*recover my_rank:*/
     332        my_rank=IssmComm::GetRank();
     333
    331334        /*Go through nodes, and for each object, report it cpu: */
    332 
    333         int i;
    334         int rank;
    335         int sid;
    336        
    337         for(i=0;i<this->Size();i++){
    338 
    339                 Node* node=(Node*)this->GetObjectByOffset(i);
    340 
    341                 /*Check that this node corresponds to our analysis currently being carried out: */
    342                 if (node->InAnalysis(analysis_type)){
    343 
    344                         rank=node->MyRank();
     335        for(int i=0;i<this->Size();i++){
     336
     337                Node* node=dynamic_cast<Node*>(this->GetObjectByOffset(i));
     338
     339                /*Check that this node corresponds to our analysis currently being carried out: */
     340                if (node->InAnalysis(analysis_type)){
     341                        /*Plug rank into ranks, according to sid: */
    345342                        sid=node->Sid();
    346 
    347                         /*Plug rank into ranks, according to id: */
    348                         ranks[sid]=rank;
    349                 }
    350         }
    351         return;
     343                        ranks[sid]=my_rank;
     344                }
     345        }
    352346}
    353347/*}}}*/
     
    358352        Node* node=NULL;
    359353
    360         for ( object=objects.begin() ; object < objects.end(); object++ ){
    361 
    362                 node=(Node*)(*object);
     354        for (object=objects.begin() ; object < objects.end(); object++ ){
     355
     356                node=dynamic_cast<Node*>(*object);
    363357                node->SetCurrentConfiguration(nodes,vertices);
    364358
    365359        }
    366 
    367 }
    368 /*}}}*/
     360}
     361/*}}}*/
  • issm/trunk/src/c/Container/Nodes.h

    r12706 r13975  
    1313        public:
    1414
    15                 /*constructors, destructors: {{{*/
     15                /*constructors, destructors*/
    1616                Nodes();
    1717                ~Nodes();
    18                 /*}}}*/
    19                 /*numerics: {{{*/
     18
     19                /*numerics*/
    2020                void  Configure(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
    2121                void  DistributeDofs(int analysis_type,int SETENUM);
     
    2323                int   MaxNumDofs(int analysis_type,int setenum);
    2424                int   NumberOfDofs(int analysis_type,int setenum);
     25                int   NumberOfDofsLocal(int analysis_type,int setenum);
    2526                int   NumberOfNodes(int analysis_type);
    2627                int   NumberOfNodes(void);
    2728                void  Ranks(int* ranks,int analysis_type);
    2829                void  SetCurrentConfiguration(Elements* elements,Loads* loads, Nodes* nodes, Vertices* vertices, Materials* materials,Parameters* parameters);
    29                 /*}}}*/
    3030
    3131};
  • issm/trunk/src/c/Container/Observations.cpp

    r13395 r13975  
    4040
    4141        /*Intermediaries*/
    42         int          i,j,maxdepth,level,counter,index;
     42        int          i,maxdepth,level,counter,index;
    4343        int          xi,yi;
    4444        IssmPDouble  xmin,xmax,ymin,ymax;
     
    8888                this->quadtree->ClosestObs(&index,x[i],y[i]);
    8989                if(index>=0){
    90                         observation=(Observation*)this->GetObjectByOffset(index);
     90                        observation=dynamic_cast<Observation*>(this->GetObjectByOffset(index));
    9191                        if(pow(observation->x-x[i],2)+pow(observation->y-y[i],2) < minspacing) continue;
    9292                }
     
    121121
    122122        /*Output and Intermediaries*/
    123         bool         stop;
    124123        int          nobs,i,index;
    125124        IssmPDouble  h2,hmin2,radius2;
     
    136135        this->quadtree->RangeSearch(&indices,&nobs,x_interp,y_interp,radius);
    137136        for (i=0;i<nobs;i++){
    138                 observation=(Observation*)this->GetObjectByOffset(indices[i]);
     137                observation=dynamic_cast<Observation*>(this->GetObjectByOffset(indices[i]));
    139138                h2 = (observation->x-x_interp)*(observation->x-x_interp) + (observation->y-y_interp)*(observation->y-y_interp);
    140139
     
    158157        }
    159158        else{
    160                 observation=(Observation*)this->GetObjectByOffset(indices[index]);
     159                observation=dynamic_cast<Observation*>(this->GetObjectByOffset(indices[index]));
    161160                *px=observation->x;
    162161                *py=observation->y;
     
    195194        nobs = 0;
    196195        for (i=0;i<tempnobs;i++){
    197                 observation=(Observation*)this->GetObjectByOffset(tempindices[i]);
     196                observation=dynamic_cast<Observation*>(this->GetObjectByOffset(tempindices[i]));
    198197                h2 = (observation->x-x_interp)*(observation->x-x_interp) + (observation->y-y_interp)*(observation->y-y_interp);
    199198
     
    237236                /*Loop over all observations and fill in x, y and obs*/
    238237                for (i=0;i<nobs;i++){
    239                         observation=(Observation*)this->GetObjectByOffset(indices[i]);
     238                        observation=dynamic_cast<Observation*>(this->GetObjectByOffset(indices[i]));
    240239                        observation->WriteXYObs(&x[i],&y[i],&obs[i]);
    241240                }
     
    266265                obs = xNew<IssmPDouble>(nobs);
    267266                for(int i=0;i<this->Size();i++){
    268                         observation=(Observation*)this->GetObjectByOffset(i);
     267                        observation=dynamic_cast<Observation*>(this->GetObjectByOffset(i));
    269268                        observation->WriteXYObs(&x[i],&y[i],&obs[i]);
    270269                }
     
    451450
    452451        for(i=0;i<this->Size();i++){
    453                 observation1=(Observation*)this->GetObjectByOffset(i);
     452                observation1=dynamic_cast<Observation*>(this->GetObjectByOffset(i));
    454453
    455454                for(j=i+1;j<this->Size();j++){
    456                         observation2=(Observation*)this->GetObjectByOffset(j);
     455                        observation2=dynamic_cast<Observation*>(this->GetObjectByOffset(j));
    457456
    458457                        distance=sqrt(pow(observation1->x - observation2->x,2.) + pow(observation1->y - observation2->y,2.));
  • issm/trunk/src/c/Container/Observations.h

    r13395 r13975  
    3737};
    3838#endif //ifndef _OBSERVATIONS_H_
    39 
  • issm/trunk/src/c/Container/Options.cpp

    r13395 r13975  
    4242
    4343        char* name=NULL;
    44        
     44
    4545        vector<Object*>::iterator object;
    4646        Option* option=NULL;
     
    6060        for(object=objects.begin();object<objects.end();object++){
    6161
    62                 option=(Option*)(*object);
     62                option=dynamic_cast<Option*>(*object);
    6363                if (!strcmp(option->Name(),name)){
    6464                        _error_("Options \"" << name << "\" found multiple times");
     
    8282        for ( object=objects.begin() ; object < objects.end(); object++ ){
    8383
    84                 option=(Option*)(*object);
     84                option=dynamic_cast<Option*>(*object);
    8585                if (!strncmp(name,option->Name(),strlen(option->Name()))){
    8686
  • issm/trunk/src/c/Container/Options.h

    r13395 r13975  
    2222                int  AddOption(Option* in_oobject);
    2323                Option* GetOption(const char* name);
    24                
    25                
     24
    2625                template <class OptionType> void Get(OptionType* pvalue,const char* name){ /*{{{*/
    2726
    28                         vector<Object*>::iterator object;
    29                         GenericOption<OptionType>* genericoption=NULL;
    30 
    3127                        /*Get option*/
    32                         genericoption=(GenericOption<OptionType>*)GetOption(name);
     28                        GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
    3329
    3430                        /*If the pointer is not NULL, the option has been found*/
     
    4440                template <class OptionType> void Get(OptionType* pvalue,int* pnumel, const char* name){ /*{{{*/
    4541
    46                         vector<Object*>::iterator object;
    47                         GenericOption<OptionType>* genericoption=NULL;
    48 
    4942                        /*Get option*/
    50                         genericoption=(GenericOption<OptionType>*)GetOption(name);
     43                        GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
    5144
    5245                        /*If the pointer is not NULL, the option has been found*/
     
    6356                template <class OptionType> void Get(OptionType* pvalue,const char* name,OptionType default_value){ /*{{{*/
    6457
    65                         vector<Object*>::iterator object;
    66                         GenericOption<OptionType>* genericoption=NULL;
    67 
    6858                        /*Get option*/
    69                         genericoption=(GenericOption<OptionType>*)GetOption(name);
     59                        GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
    7060
    7161                        /*If the pointer is not NULL, the option has been found*/
     
    8070                template <class OptionType> void Get(OptionType* pvalue,int* pnumel, const char* name,OptionType default_value){ /*{{{*/
    8171
    82                         vector<Object*>::iterator object;
    83                         GenericOption<OptionType>* genericoption=NULL;
    84 
    8572                        /*Get option*/
    86                         genericoption=(GenericOption<OptionType>*)GetOption(name);
     73                        GenericOption<OptionType>* genericoption=dynamic_cast<GenericOption<OptionType>*>(GetOption(name));
    8774
    8875                        /*If the pointer is not NULL, the option has been found*/
     
    10390template <> inline void Options::Get(char** pvalue,const char* name,char* default_value){ /*{{{*/
    10491
    105         vector<Object*>::iterator object;
    106         GenericOption<char*>* genericoption=NULL;
    107 
    10892        /*Get option*/
    109         genericoption=(GenericOption<char*>*)GetOption(name);
     93        GenericOption<char*>* genericoption=dynamic_cast<GenericOption<char*>*>(GetOption(name));
    11094
    11195        /*If the pointer is not NULL, the option has been found*/
     
    11599        else{
    116100                /*Make a copy*/
    117                 char* outstring=NULL;
    118                 int   stringsize;
    119 
    120                 stringsize=strlen(default_value)+1;
    121                 outstring=xNew<char>(stringsize);
     101                int   stringsize=strlen(default_value)+1;
     102                char* outstring=xNew<char>(stringsize);
    122103                xMemCpy<char>(outstring,default_value,stringsize);
    123104                *pvalue=outstring;
  • issm/trunk/src/c/Container/Parameters.cpp

    r13395 r13975  
    4545
    4646        for ( object=objects.begin() ; object < objects.end(); object++ ){
    47                 param=(Param*)(*object);
     47                param=dynamic_cast<Param*>(*object);
    4848                if(param->InstanceEnum()==enum_type) return true;
    4949        }
     
    5353/*FUNCTION Parameters::FindParam(bool* pbool,int enum_type){{{*/
    5454void Parameters::FindParam(bool* pbool,int enum_type){ _assert_(this);
    55        
    56         vector<Object*>::iterator object;
    57         Param* param=NULL;
    58 
    59         for ( object=objects.begin() ; object < objects.end(); object++ ){
    60 
    61                 param=(Param*)(*object);
     55
     56        vector<Object*>::iterator object;
     57        Param* param=NULL;
     58
     59        for ( object=objects.begin() ; object < objects.end(); object++ ){
     60
     61                param=dynamic_cast<Param*>(*object);
    6262                if(param->InstanceEnum()==enum_type){
    6363                        param->GetParameterValue(pbool);
     
    7070/*FUNCTION Parameters::FindParam(int* pinteger,int enum_type){{{*/
    7171void Parameters::FindParam(int* pinteger,int enum_type){ _assert_(this);
    72        
    73         vector<Object*>::iterator object;
    74         Param* param=NULL;
    75 
    76         for ( object=objects.begin() ; object < objects.end(); object++ ){
    77 
    78                 param=(Param*)(*object);
     72
     73        vector<Object*>::iterator object;
     74        Param* param=NULL;
     75
     76        for ( object=objects.begin() ; object < objects.end(); object++ ){
     77
     78                param=dynamic_cast<Param*>(*object);
    7979                if(param->InstanceEnum()==enum_type){
    8080                        param->GetParameterValue(pinteger);
     
    8787/*FUNCTION Parameters::FindParam(IssmDouble* pscalar, int enum_type){{{*/
    8888void Parameters::FindParam(IssmDouble* pscalar, int enum_type){ _assert_(this);
    89        
    90         vector<Object*>::iterator object;
    91         Param* param=NULL;
    92 
    93         for ( object=objects.begin() ; object < objects.end(); object++ ){
    94 
    95                 param=(Param*)(*object);
     89
     90        vector<Object*>::iterator object;
     91        Param* param=NULL;
     92
     93        for ( object=objects.begin() ; object < objects.end(); object++ ){
     94
     95                param=dynamic_cast<Param*>(*object);
    9696                if(param->InstanceEnum()==enum_type){
    9797                        param->GetParameterValue(pscalar);
     
    110110        for ( object=objects.begin() ; object < objects.end(); object++ ){
    111111
    112                 param=(Param*)(*object);
     112                param=dynamic_cast<Param*>(*object);
    113113                if(param->InstanceEnum()==enum_type){
    114114                        param->GetParameterValue(pscalar,time);
     
    121121/*FUNCTION Parameters::FindParam(char** pstring,int enum_type){{{*/
    122122void Parameters::FindParam(char** pstring,int enum_type){ _assert_(this);
    123        
    124         vector<Object*>::iterator object;
    125         Param* param=NULL;
    126 
    127         for ( object=objects.begin() ; object < objects.end(); object++ ){
    128 
    129                 param=(Param*)(*object);
     123
     124        vector<Object*>::iterator object;
     125        Param* param=NULL;
     126
     127        for ( object=objects.begin() ; object < objects.end(); object++ ){
     128
     129                param=dynamic_cast<Param*>(*object);
    130130                if(param->InstanceEnum()==enum_type){
    131131                        param->GetParameterValue(pstring);
     
    139139/*FUNCTION Parameters::FindParam(char*** pstringarray,int* pM,int enum_type){{{*/
    140140void Parameters::FindParam(char*** pstringarray,int* pM,int enum_type){ _assert_(this);
    141        
    142         vector<Object*>::iterator object;
    143         Param* param=NULL;
    144 
    145         for ( object=objects.begin() ; object < objects.end(); object++ ){
    146 
    147                 param=(Param*)(*object);
     141
     142        vector<Object*>::iterator object;
     143        Param* param=NULL;
     144
     145        for ( object=objects.begin() ; object < objects.end(); object++ ){
     146
     147                param=dynamic_cast<Param*>(*object);
    148148                if(param->InstanceEnum()==enum_type){
    149149                        param->GetParameterValue(pstringarray,pM);
     
    163163        for ( object=objects.begin() ; object < objects.end(); object++ ){
    164164
    165                 param=(Param*)(*object);
     165                param=dynamic_cast<Param*>(*object);
    166166                if(param->InstanceEnum()==enum_type){
    167167                        param->GetParameterValue(pintarray,pM);
     
    181181        for ( object=objects.begin() ; object < objects.end(); object++ ){
    182182
    183                 param=(Param*)(*object);
     183                param=dynamic_cast<Param*>(*object);
    184184                if(param->InstanceEnum()==enum_type){
    185185                        param->GetParameterValue(pintarray,pM,pN);
     
    199199        for ( object=objects.begin() ; object < objects.end(); object++ ){
    200200
    201                 param=(Param*)(*object);
     201                param=dynamic_cast<Param*>(*object);
    202202                if(param->InstanceEnum()==enum_type){
    203203                        param->GetParameterValue(pIssmDoublearray,pM);
     
    217217        for ( object=objects.begin() ; object < objects.end(); object++ ){
    218218
    219                 param=(Param*)(*object);
     219                param=dynamic_cast<Param*>(*object);
    220220                if(param->InstanceEnum()==enum_type){
    221221                        param->GetParameterValue(pIssmDoublearray,pM,pN);
     
    229229/*FUNCTION Parameters::FindParam(IssmDouble*** parray,int* pM,int** pmdims_array,int** pndims_array,int enum_type){{{*/
    230230void Parameters::FindParam(IssmDouble*** parray,int* pM,int** pmdims_array,int** pndims_array,int enum_type){ _assert_(this);
    231        
    232         vector<Object*>::iterator object;
    233         Param* param=NULL;
    234 
    235         for ( object=objects.begin() ; object < objects.end(); object++ ){
    236 
    237                 param=(Param*)(*object);
     231
     232        vector<Object*>::iterator object;
     233        Param* param=NULL;
     234
     235        for ( object=objects.begin() ; object < objects.end(); object++ ){
     236
     237                param=dynamic_cast<Param*>(*object);
    238238                if(param->InstanceEnum()==enum_type){
    239239                        param->GetParameterValue(parray,pM,pmdims_array,pndims_array);
     
    246246/*FUNCTION Parameters::FindParam(Vector<IssmDouble>** pvec,int enum_type){{{*/
    247247void Parameters::FindParam(Vector<IssmDouble>** pvec,int enum_type){ _assert_(this);
    248        
    249         vector<Object*>::iterator object;
    250         Param* param=NULL;
    251 
    252         for ( object=objects.begin() ; object < objects.end(); object++ ){
    253 
    254                 param=(Param*)(*object);
     248
     249        vector<Object*>::iterator object;
     250        Param* param=NULL;
     251
     252        for ( object=objects.begin() ; object < objects.end(); object++ ){
     253
     254                param=dynamic_cast<Param*>(*object);
    255255                if(param->InstanceEnum()==enum_type){
    256256                        param->GetParameterValue(pvec);
     
    264264/*FUNCTION Parameters::FindParam(Matrix<IssmDouble>** pmat,int enum_type){{{*/
    265265void Parameters::FindParam(Matrix<IssmDouble>** pmat,int enum_type){ _assert_(this);
    266        
    267         vector<Object*>::iterator object;
    268         Param* param=NULL;
    269 
    270         for ( object=objects.begin() ; object < objects.end(); object++ ){
    271 
    272                 param=(Param*)(*object);
     266
     267        vector<Object*>::iterator object;
     268        Param* param=NULL;
     269
     270        for ( object=objects.begin() ; object < objects.end(); object++ ){
     271
     272                param=dynamic_cast<Param*>(*object);
    273273                if(param->InstanceEnum()==enum_type){
    274274                        param->GetParameterValue(pmat);
     
    288288        for ( object=objects.begin() ; object < objects.end(); object++ ){
    289289
    290                 param=(Param*)(*object);
     290                param=dynamic_cast<Param*>(*object);
    291291                if(param->InstanceEnum()==enum_type){
    292292                        param->GetParameterValue(pfid);
     293                        return;
     294                }
     295        }
     296        _error_("could not find parameter " << EnumToStringx(enum_type));
     297}
     298/*}}}*/
     299/*FUNCTION Parameters::FindParam(DataSet** pdataset,int enum_type){{{*/
     300void Parameters::FindParam(DataSet** pdataset,int enum_type){
     301        _assert_(this);
     302
     303        vector<Object*>::iterator object;
     304        Param* param=NULL;
     305
     306        for ( object=objects.begin() ; object < objects.end(); object++ ){
     307
     308                param=dynamic_cast<Param*>(*object);
     309                if(param->InstanceEnum()==enum_type){
     310                        param->GetParameterValue(pdataset);
    293311                        return;
    294312                }
     
    302320
    303321        Param* param=NULL;
    304        
    305         /*first, figure out if the param has already been created: */
    306         param=(Param*)this->FindParamObject(enum_type);
     322
     323        /*first, figure out if the param has already been created: */
     324        param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
    307325
    308326        if(param) param->SetValue(boolean); //already exists, just set it.
     
    314332
    315333        Param* param=NULL;
    316        
    317         /*first, figure out if the param has already been created: */
    318         param=(Param*)this->FindParamObject(enum_type);
     334
     335        /*first, figure out if the param has already been created: */
     336        param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
    319337
    320338        if(param) param->SetValue(integer); //already exists, just set it.
     
    326344
    327345        Param* param=NULL;
    328        
    329         /*first, figure out if the param has already been created: */
    330         param=(Param*)this->FindParamObject(enum_type);
     346
     347        /*first, figure out if the param has already been created: */
     348        param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
    331349
    332350        if(param) param->SetValue(scalar); //already exists, just set it.
     
    338356
    339357        Param* param=NULL;
    340        
    341         /*first, figure out if the param has already been created: */
    342         param=(Param*)this->FindParamObject(enum_type);
     358
     359        /*first, figure out if the param has already been created: */
     360        param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
    343361
    344362        if(param) param->SetValue(string); //already exists, just set it.
     
    350368
    351369        Param* param=NULL;
    352        
    353         /*first, figure out if the param has already been created: */
    354         param=(Param*)this->FindParamObject(enum_type);
     370
     371        /*first, figure out if the param has already been created: */
     372        param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
    355373
    356374        if(param) param->SetValue(stringarray,M); //already exists, just set it.
     
    362380
    363381        Param* param=NULL;
    364        
    365         /*first, figure out if the param has already been created: */
    366         param=(Param*)this->FindParamObject(enum_type);
     382
     383        /*first, figure out if the param has already been created: */
     384        param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
    367385
    368386        if(param) param->SetValue(IssmDoublearray,M); //already exists, just set it.
     
    374392
    375393        Param* param=NULL;
    376        
    377         /*first, figure out if the param has already been created: */
    378         param=(Param*)this->FindParamObject(enum_type);
     394
     395        /*first, figure out if the param has already been created: */
     396        param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
    379397
    380398        if(param) param->SetValue(IssmDoublearray,M,N); //already exists, just set it.
     
    388406
    389407        /*first, figure out if the param has already been created: */
    390         param=(Param*)this->FindParamObject(enum_type);
     408        param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
    391409
    392410        if(param) param->SetValue(intarray,M); //already exists, just set it.
     
    400418
    401419        /*first, figure out if the param has already been created: */
    402         param=(Param*)this->FindParamObject(enum_type);
     420        param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
    403421
    404422        if(param) param->SetValue(intarray,M,N); //already exists, just set it.
     
    410428
    411429        Param* param=NULL;
    412        
    413         /*first, figure out if the param has already been created: */
    414         param=(Param*)this->FindParamObject(enum_type);
     430
     431        /*first, figure out if the param has already been created: */
     432        param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
    415433
    416434        if(param) param->SetValue(vector); //already exists, just set it.
     
    422440
    423441        Param* param=NULL;
    424        
    425         /*first, figure out if the param has already been created: */
    426         param=(Param*)this->FindParamObject(enum_type);
     442
     443        /*first, figure out if the param has already been created: */
     444        param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
    427445
    428446        if(param) param->SetValue(matrix); //already exists, just set it.
     
    436454
    437455        /*first, figure out if the param has already been created: */
    438         param=(Param*)this->FindParamObject(enum_type);
     456        param=dynamic_cast<Param*>(this->FindParamObject(enum_type));
    439457
    440458        if(param) param->SetValue(fid); //already exists, just set it.
     
    449467
    450468        for ( object=objects.begin() ; object < objects.end(); object++ ){
    451                 param=(Param*)(*object);
     469                param=dynamic_cast<Param*>(*object);
    452470                param->UnitConversion(direction_enum);
    453471        }
     
    464482        for ( object=objects.begin() ; object < objects.end(); object++ ){
    465483
    466                 param=(Param*)(*object);
     484                param=dynamic_cast<Param*>(*object);
    467485                if(param->InstanceEnum()==enum_type){
    468486                        return (*object);
  • issm/trunk/src/c/Container/Parameters.h

    r13395 r13975  
    4444                void  FindParam(Matrix<IssmDouble>** pmat,int enum_type);
    4545                void  FindParam(FILE** pfid,int enum_type);
    46                
     46                void  FindParam(DataSet** pdataset, int enum_type);
     47
    4748                void  SetParam(bool boolean,int enum_type);
    4849                void  SetParam(int integer,int enum_type);
  • issm/trunk/src/c/Container/Results.cpp

    r12706 r13975  
    6666/*FUNCTION Results::Write{{{*/
    6767void Results::Write(Parameters* parameters){
    68        
     68
    6969        int         i;
    7070        FILE       *fid          = NULL;
     
    7676
    7777        for(i=0;i<this->Size();i++){
    78                 ExternalResult* result=(ExternalResult*)this->GetObjectByOffset(i);
     78                ExternalResult* result=dynamic_cast<ExternalResult*>(this->GetObjectByOffset(i));
    7979
    8080                /*write result to disk: */
  • issm/trunk/src/c/Container/Results.h

    r12706 r13975  
    2020        public:
    2121
    22                 /*constructors, destructors: {{{*/
     22                /*constructors, destructors*/
    2323                Results();
    2424                ~Results();
    25                 /*}}}*/
    26                 /*numerics: {{{*/
     25
     26                /*numerics*/
    2727                Results* SpawnTriaResults(int* indices);
    28                 void Write(Parameters* parameters);
    29                 /*}}}*/
     28                void     Write(Parameters* parameters);
    3029};
    3130#endif //ifndef _RESULTS_H_
    32 
  • issm/trunk/src/c/Container/Vertices.cpp

    r12706 r13975  
    3838
    3939/*Numerics management*/
    40 /*FUNCTION Vertices::DistributeDofs{{{*/
    41 void  Vertices::DistributeDofs(int numberofobjects,int numberofdofsperobject){
    42 
    43         extern int num_procs;
    44         extern int my_rank;
     40/*FUNCTION Vertices::DistributePids{{{*/
     41void  Vertices::DistributePids(int numberofobjects){
     42
     43        int num_procs;
     44        int my_rank;
    4545
    4646        int  i;
    47         int  dofcount=0;
    48         int* alldofcount=NULL;
    49         int* truedofs=NULL;
    50         int* alltruedofs=NULL;
    51 
    52         /*Go through objects, and distribute dofs locally, from 0 to numberofdofsperobject*/
     47        int  pidcount    = 0;
     48        int *allpidcount = NULL;
     49        int *truepids    = NULL;
     50        int *alltruepids = NULL;
     51
     52        /*recover my_rank:*/
     53        my_rank=IssmComm::GetRank();
     54        num_procs=IssmComm::GetSize();
     55
     56        /*Go through objects, and distribute pids locally, from 0 to numberofpidsperobject*/
    5357        for (i=0;i<this->Size();i++){
    54                 Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
    55                 vertex->DistributeDofs(&dofcount);
    56         }
    57 
    58         /* Now every object has distributed dofs, but locally, and with a dof count starting from
    59          * 0. This means the dofs between all the cpus are not unique. We now offset the dofs of eache
    60          * cpus by the total last dofs of the previus cpu, starting from 0.
    61          * First: bet number of dofs for each cpu*/
    62         alldofcount=xNew<int>(num_procs);
    63         #ifdef _HAVE_MPI_
    64         MPI_Gather(&dofcount,1,MPI_INT,alldofcount,1,MPI_INT,0,MPI_COMM_WORLD);
    65         MPI_Bcast(alldofcount,num_procs,MPI_INT,0,MPI_COMM_WORLD);
     58                Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
     59                vertex->DistributePids(&pidcount);
     60        }
     61
     62        /* Now every object has distributed pids, but locally, and with a pid count starting from
     63         * 0. This means the pids between all the cpus are not unique. We now offset the pids of each
     64         * cpus by the total last pids of the previus cpu, starting from 0.
     65         * First: get number of pids for each cpu*/
     66        allpidcount=xNew<int>(num_procs);
     67        #ifdef _HAVE_MPI_
     68        MPI_Gather(&pidcount,1,MPI_INT,allpidcount,1,MPI_INT,0,IssmComm::GetComm());
     69        MPI_Bcast(allpidcount,num_procs,MPI_INT,0,IssmComm::GetComm());
    6670        #else
    67         alldofcount[0]=dofcount;
    68         #endif
    69 
    70         /* Every cpu should start its own dof count at the end of the dofcount from cpu-1*/
    71         dofcount=0;
     71        allpidcount[0]=pidcount;
     72        #endif
     73
     74        /* Every cpu should start its own pid count at the end of the pidcount from cpu-1*/
     75        pidcount=0;
    7276        if(my_rank!=0){
    7377                for(i=0;i<my_rank;i++){
    74                         dofcount+=alldofcount[i];
     78                        pidcount+=allpidcount[i];
    7579                }
    7680        }
    7781        for (i=0;i<this->Size();i++){
    78                 Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
    79                 vertex->OffsetDofs(dofcount);
     82                Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
     83                vertex->OffsetPids(pidcount);
    8084        }
    8185
    8286        /* Finally, remember that cpus may have skipped some objects, because they were clones. For every
    83          * object that is not a clone, tell them to show their dofs, so that later on, they can get picked
     87         * object that is not a clone, tell them to show their pids, so that later on, they can get picked
    8488         * up by their clones: */
    85         truedofs   =xNewZeroInit<int>(numberofobjects*numberofdofsperobject);
    86         alltruedofs=xNewZeroInit<int>(numberofobjects*numberofdofsperobject);
     89        truepids   =xNewZeroInit<int>(numberofobjects);
     90        alltruepids=xNewZeroInit<int>(numberofobjects);
    8791        for (i=0;i<this->Size();i++){
    88                 Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
    89                 vertex->ShowTrueDofs(truedofs);
    90         }
    91         #ifdef _HAVE_MPI_
    92         MPI_Allreduce((void*)truedofs,(void*)alltruedofs,numberofobjects*numberofdofsperobject,MPI_INT,MPI_MAX,MPI_COMM_WORLD);
     92                Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
     93                vertex->ShowTruePids(truepids);
     94        }
     95        #ifdef _HAVE_MPI_
     96        MPI_Allreduce((void*)truepids,(void*)alltruepids,numberofobjects,MPI_INT,MPI_MAX,IssmComm::GetComm());
    9397        #else
    94         for(i=0;i<numberofobjects*numberofdofsperobject;i++)alltruedofs[i]=truedofs[i];
    95         #endif
    96 
    97         /* Now every cpu knows the true dofs of everyone else that is not a clone*/
    98         for (i=0;i<this->Size();i++){
    99                 Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
    100                 vertex->UpdateCloneDofs(alltruedofs);
     98        for(i=0;i<numberofobjects;i++)alltruepids[i]=truepids[i];
     99        #endif
     100
     101        /* Now every cpu knows the true pids of everyone else that is not a clone*/
     102        for(i=0;i<this->Size();i++){
     103                Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
     104                vertex->UpdateClonePids(alltruepids);
    101105        }
    102106
    103107        /* Free ressources: */
    104         xDelete<int>(alldofcount);
    105         xDelete<int>(truedofs);
    106         xDelete<int>(alltruedofs);
     108        xDelete<int>(allpidcount);
     109        xDelete<int>(truepids);
     110        xDelete<int>(alltruepids);
    107111}
    108112/*}}}*/
     
    111115
    112116        int i;
    113         extern int num_procs;
     117        int num_procs;
    114118
    115119        int* ranks=NULL;
    116120        int* minranks=NULL;
     121
     122        /*recover num_procs:*/
     123        num_procs=IssmComm::GetSize();
    117124
    118125        /*Allocate ranks: */
     
    130137         * order of cpu rank. This is also why we initialized this array to num_procs.*/
    131138        #ifdef _HAVE_MPI_
    132         MPI_Allreduce ( (void*)ranks,(void*)minranks,numberofobjects,MPI_INT,MPI_MIN,MPI_COMM_WORLD);
     139        MPI_Allreduce ( (void*)ranks,(void*)minranks,numberofobjects,MPI_INT,MPI_MIN,IssmComm::GetComm());
    133140        #else
    134141        for(i=0;i<numberofobjects;i++)minranks[i]=ranks[i];
     
    138145        for(i=0;i<this->Size();i++){
    139146                /*For this object, decide whether it is a clone: */
    140                 Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
     147                Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
    141148                vertex->SetClone(minranks);
    142149        }
     
    156163
    157164        for(i=0;i<this->Size();i++){
    158                 Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
     165                Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
    159166                sid=vertex->Sid();
    160167                if (sid>max_sid)max_sid=sid;
     
    162169
    163170        #ifdef _HAVE_MPI_
    164         MPI_Reduce (&max_sid,&vertex_max_sid,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD );
    165         MPI_Bcast(&vertex_max_sid,1,MPI_INT,0,MPI_COMM_WORLD);
     171        MPI_Reduce (&max_sid,&vertex_max_sid,1,MPI_INT,MPI_MAX,0,IssmComm::GetComm() );
     172        MPI_Bcast(&vertex_max_sid,1,MPI_INT,0,IssmComm::GetComm());
    166173        max_sid=vertex_max_sid;
    167174        #endif
     
    177184void   Vertices::Ranks(int* ranks){
    178185
     186        int my_rank;
     187        int        sid;
     188
     189        /*recover my_rank:*/
     190        my_rank=IssmComm::GetRank();
     191
    179192        /*Go through a dataset, and for each object, report it cpu: */
    180 
    181         int i;
    182         int rank;
    183         int sid;
    184        
    185         for(i=0;i<this->Size();i++){
    186                 Vertex* vertex=(Vertex*)this->GetObjectByOffset(i);
    187                 rank=vertex->MyRank();
     193        for(int i=0;i<this->Size();i++){
     194                /*Plug rank into ranks, according to id: */
     195                Vertex* vertex=dynamic_cast<Vertex*>(this->GetObjectByOffset(i));
    188196                sid=vertex->Sid();
    189                
    190                 /*Plug rank into ranks, according to id: */
    191                 ranks[sid]=rank;
    192         }
    193         return;
    194 }
    195 /*}}}*/
     197                ranks[sid]=my_rank;
     198        }
     199}
     200/*}}}*/
  • issm/trunk/src/c/Container/Vertices.h

    r12706 r13975  
    1919        public:
    2020
    21                 /*constructors, destructors: {{{*/
     21                /*constructors, destructors:*/
    2222                Vertices();
    2323                ~Vertices();
    24                 /*}}}*/
    25                 /*numerics: {{{*/
    26                 void  DistributeDofs(int numberofnodes,int numdofspernode);
     24
     25                /*numerics:*/
     26                void  DistributePids(int numberofnodes);
    2727                void  FlagClones(int numberofnodes);
    2828                int   NumberOfVertices(void);
    2929                void  Ranks(int* ranks);
    30                 /*}}}*/
    31 
    3230};
    3331
  • issm/trunk/src/c/EnumDefinitions/EnumDefinitions.h

    r13395 r13975  
    1313        /*Model fields {{{1*/
    1414        AutodiffIsautodiffEnum,
    15         AutodiffDependentsEnum,
    1615        AutodiffNumDependentsEnum,
    17         AutodiffIndependentsEnum,
     16        AutodiffNumDependentObjectsEnum,
     17        AutodiffDependentObjectNamesEnum,
     18        AutodiffDependentObjectTypesEnum,
     19        AutodiffDependentObjectIndicesEnum,
     20        AutodiffDependentObjectsEnum,
    1821        AutodiffNumIndependentsEnum,
     22        AutodiffNumIndependentObjectsEnum,
     23        AutodiffIndependentObjectNamesEnum,
     24        AutodiffIndependentObjectTypesEnum,
     25        AutodiffIndependentObjectsEnum,
    1926        AutodiffJacobianEnum,
    2027        AutodiffXpEnum,
    21         AutodiffFosForwardOutputEnum,
     28        AutodiffDriverEnum,
     29        AutodiffFosForwardIndexEnum,
     30        AutodiffFovForwardIndicesEnum,
     31        AutodiffFosReverseIndexEnum,
     32        AutodiffMassFluxSegmentsPresentEnum,
     33        AutodiffKeepEnum,
    2234        BalancethicknessSpcthicknessEnum,
    2335        BalancethicknessStabilizationEnum,
     
    3143        ConstantsReferencetemperatureEnum,
    3244        ConstantsYtsEnum,
     45        DependentObjectEnum,
    3346        DiagnosticAbstolEnum,
    3447        DiagnosticIcefrontEnum,
     
    7083        HydrologySpcwatercolumnEnum,
    7184        HydrologyStabilizationEnum,
     85        IndependentObjectEnum,
    7286        InversionControlParametersEnum,
    7387        InversionCostFunctionEnum,
     
    143157        PrognosticStabilizationEnum,
    144158        PrognosticVertexPairingEnum,
     159        PrognosticNumRequestedOutputsEnum,
     160        PrognosticRequestedOutputsEnum,
    145161        QmuIsdakotaEnum,
    146         QmuMassFluxSegmentsEnum,
     162        MassFluxSegmentsEnum,
     163        MassFluxSegmentsPresentEnum,
     164        QmuMassFluxSegmentsPresentEnum,
    147165        QmuNumberofpartitionsEnum,
    148166        QmuNumberofresponsesEnum,
     
    179197        SurfaceforcingsMonthlytemperaturesEnum,
    180198        SurfaceforcingsHcEnum,
     199        SurfaceforcingsHrefEnum,
     200        SurfaceforcingsSmbrefEnum,
    181201        SurfaceforcingsSmbPosMaxEnum,
    182202        SurfaceforcingsSmbPosMinEnum,
     
    273293        DofIndexingEnum,
    274294        DoubleInputEnum,
     295        DataSetParamEnum,
    275296        DoubleMatArrayParamEnum,
    276297        DoubleMatParamEnum,
     
    302323        PentaEnum,
    303324        PentaP1InputEnum,
     325        ProfilerEnum,
    304326        MatrixParamEnum,
    305327        VectorParamEnum,
     
    490512        OldGradientEnum,
    491513        OutputFilePointerEnum,
     514        OutputFileNameEnum,
     515        LockFileNameEnum,
    492516        PetscOptionsAnalysesEnum,
    493517        PetscOptionsStringsEnum,
  • issm/trunk/src/c/Makefile.am

    r13395 r13975  
    1 AM_CPPFLAGS = @DAKOTAINCL@ @SHAPELIBINCL@ @PETSCINCL@ @SLEPCINCL@ @MPIINCL@ @MATLABINCL@ @METISINCL@ @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@ @BLASLAPACKINCL@ @MKLINCL@ @MUMPSINCL@ @TRIANGLEINCL@ @SPAIINCL@ @HYPREINCL@ @PROMETHEUSINCL@ @SUPERLUINCL@ @SPOOLESINCL@ @PASTIXINCL@ @MLINCL@ @TAOINCL@ @ADIC2INCL@ @ADOLCINCL@ @GSLINCL@ @BOOSTINCL@ @PYTHONINCL@ @PYTHON_NUMPYINCL@
     1AM_CPPFLAGS = @DAKOTAINCL@ @SHAPELIBINCL@ @PETSCINCL@ @SLEPCINCL@ @MPIINCL@ @METISINCL@ @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@ @BLASLAPACKINCL@ @MKLINCL@ @MUMPSINCL@ @TRIANGLEINCL@ @SPAIINCL@ @HYPREINCL@ @PROMETHEUSINCL@ @SUPERLUINCL@ @SPOOLESINCL@ @PASTIXINCL@ @MLINCL@ @TAOINCL@ @ADIC2INCL@ @ADOLCINCL@ @GSLINCL@ @BOOSTINCL@
    22
    33EXEEXT=$(ISSMEXT)
     
    99lib_LTLIBRARIES = libISSMCore.la libISSMOverload.la libISSM.la
    1010endif
    11 if PYTHON
    12 lib_LIBRARIES += libISSMPython.a
    13 endif
    14 if MATLAB
    15 if SHAREDLIBS
    16 lib_LTLIBRARIES += libISSMMatlab.la
    17 endif
    18 lib_LIBRARIES += libISSMMatlab.a
    19 endif
    20 if MODULES
     11if WRAPPERS
    2112if SHAREDLIBS
    2213lib_LTLIBRARIES += libISSMModules.la
     
    5445                                        ./classes/objects/Constraints/SpcTransient.cpp\
    5546                                        ./classes/objects/Constraints/SpcTransient.h\
     47                                        ./classes/objects/IndependentObject.h\
     48                                        ./classes/objects/IndependentObject.cpp\
     49                                        ./classes/objects/DependentObject.h\
     50                                        ./classes/objects/DependentObject.cpp\
    5651                                        ./classes/DofIndexing.h\
    5752                                        ./classes/DofIndexing.cpp\
     
    6358                                        ./classes/objects/Vertex.h\
    6459                                        ./classes/objects/Vertex.cpp\
     60                                        ./classes/objects/AdolcEdf.h\
     61                                        ./classes/IssmComm.h\
     62                                        ./classes/IssmComm.cpp\
    6563                                        ./classes/Hook.h\
    6664                                        ./classes/Hook.cpp\
     
    152150                                        ./classes/objects/Params/TransientParam.h\
    153151                                        ./classes/objects/Params/TransientParam.cpp\
     152                                        ./classes/objects/Params/DataSetParam.h\
     153                                        ./classes/objects/Params/DataSetParam.cpp\
     154                                        ./classes/objects/Profiler.h\
     155                                        ./classes/objects/Profiler.cpp\
    154156                                        ./Container/Container.h\
    155157                                        ./Container/Constraints.h\
     
    182184                                        ./shared/Matrix/matrix.h\
    183185                                        ./shared/Matrix/MatrixUtils.cpp\
    184                                         ./shared/Numerics/adolc_edf.h\
    185186                                        ./shared/Numerics/numerics.h\
    186187                                        ./shared/Numerics/Verbosity.h\
     
    213214                                        ./shared/Elements/ComputeDelta18oTemperaturePrecipitation.cpp\
    214215                                        ./shared/String/sharedstring.h\
    215                                         ./shared/Wrapper/wrappershared.h\
    216                                         ./shared/Wrapper/ModuleBoot.cpp\
    217                                         ./shared/Wrapper/ModuleEnd.cpp\
    218                                         ./shared/Sys/sys.h\
    219                                         ./shared/Sys/ProfilingStart.cpp\
    220                                         ./shared/Sys/ProfilingEnd.cpp\
     216                                        ./shared/String/DescriptorIndex.cpp\
    221217                                        ./toolkits/metis/metisincludes.h\
    222218                                        ./toolkits/issm/issmtoolkit.h\
     
    230226                                        ./io/Disk/pfopen.cpp\
    231227                                        ./io/Disk/pfclose.cpp\
     228                                        ./io/Disk/WriteLockFile.cpp\
    232229                                        ./io/PrintfFunction.cpp\
    233230                                        ./EnumDefinitions/EnumDefinitions.h\
     
    279276                                        ./modules/InputArtificialNoisex/InputArtificialNoisex.h\
    280277                                        ./modules/InputArtificialNoisex/InputArtificialNoisex.cpp\
    281                                         ./modules/TimeAdaptx/TimeAdaptx.h\
    282                                         ./modules/TimeAdaptx/TimeAdaptx.cpp\
    283                                         ./modules/UpdateVertexPositionsx/UpdateVertexPositionsx.h\
    284                                         ./modules/UpdateVertexPositionsx/UpdateVertexPositionsx.cpp\
    285278                                        ./modules/ConfigureObjectsx/ConfigureObjectsx.h\
    286279                                        ./modules/ConfigureObjectsx/ConfigureObjectsx.cpp\
     
    297290                                        ./modules/SmbGradientsx/SmbGradientsx.h\
    298291                                        ./modules/SmbGradientsx/SmbGradientsx.cpp\
    299                                         ./modules/UpdateConstraintsx/UpdateConstraintsx.h\
    300                                         ./modules/UpdateConstraintsx/UpdateConstraintsx.cpp\
    301292                                        ./modules/MeshPartitionx/MeshPartitionx.h\
    302293                                        ./modules/Reducevectorgtofx/Reducevectorgtofx.cpp\
     
    308299                                        ./modules/StringToEnumx/StringToEnumx.cpp\
    309300                                        ./modules/StringToEnumx/StringToEnumx.h\
    310                                         ./modules/SystemMatricesx/SystemMatricesx.cpp\
    311                                         ./modules/SystemMatricesx/SystemMatricesx.h\
    312                                         ./modules/CreateJacobianMatrixx/CreateJacobianMatrixx.cpp\
    313                                         ./modules/CreateJacobianMatrixx/CreateJacobianMatrixx.h\
    314301                                        ./modules/ConstraintsStatex/ConstraintsStatex.cpp\
    315302                                        ./modules/ConstraintsStatex/ConstraintsStatex.h\
    316303                                        ./modules/ConstraintsStatex/ConstraintsStateLocal.h\
    317                                         ./modules/Responsex/Responsex.h\
    318                                         ./modules/Responsex/Responsex.cpp\
    319                                         ./modules/RequestedOutputsx/RequestedOutputsx.h\
    320                                         ./modules/RequestedOutputsx/RequestedOutputsx.cpp\
    321                                         ./modules/RequestedDependentsx/RequestedDependentsx.h\
    322                                         ./modules/RequestedDependentsx/RequestedDependentsx.cpp\
    323                                         ./modules/AutodiffDriversx/AutodiffDriversx.h\
    324                                         ./modules/AutodiffDriversx/AutodiffDriversx.cpp\
    325304                                        ./modules/ResetConstraintsx/ResetConstraintsx.h\
    326305                                        ./modules/ResetConstraintsx/ResetConstraintsx.cpp\
     
    340319                                        ./solutions/convergence.cpp\
    341320                                        ./solutions/ProcessArguments.cpp\
    342                                         ./solutions/WriteLockFile.cpp\
    343321                                        ./solutions/ResetBoundaryConditions.cpp\
    344322                                        ./solutions/AnalysisConfiguration.cpp\
     323                                        ./solutions/WrapperCorePointerFromSolutionEnum.cpp\
    345324                                        ./solutions/CorePointerFromSolutionEnum.cpp\
     325                                        ./solutions/EnvironmentInit.cpp\
     326                                        ./solutions/EnvironmentFinalize.cpp\
     327                                        ./solutions/ad_core.cpp\
    346328                                        ./solvers/solver_linear.cpp\
    347329                                        ./solvers/solver_nonlinear.cpp\
     
    350332                                        ./classes/objects/Options/GenericOption.h\
    351333                                        ./classes/objects/Options/OptionUtilities.cpp\
    352                                         ./classes/objects/Options/OptionUtilities.h
    353 
     334                                        ./classes/objects/Options/OptionUtilities.h\
     335                                        ./classes/RiftStruct.cpp\
     336                                        ./classes/RiftStruct.h
    354337#}}}
    355338#DAKOTA sources  {{{
     
    358341                                          ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h\
    359342                                          ./modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp\
    360                                           ./modules/DakotaResponsesx/DakotaResponsesx.h\
    361                                           ./modules/DakotaResponsesx/DakotaResponsesx.cpp\
    362343                                          ./modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h\
    363344                                          ./modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp\
     
    366347                                          ./modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp\
    367348                                          ./modules/AverageOntoPartitionx/AverageOntoPartitionx.h\
    368                                           ./modules/Dakotax/Dakotax.h\
    369                                           ./modules/Dakotax/Dakotax.cpp\
    370                                           ./modules/Dakotax/DakotaMPI_Bcast.cpp\
    371                                           ./modules/Dakotax/DakotaFree.cpp\
    372                                           ./modules/Dakotax/SpawnCore.cpp\
    373                                           ./modules/Dakotax/DescriptorIndex.cpp\
    374349                                          ./modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp\
    375                                           ./modules/Dakotax/SpawnCoreParallel.cpp
     350                                          ./solutions/dakota_core.cpp\
     351                                          ./solutions/DakotaSpawnCore.cpp
    376352#}}}
    377353#Transient sources  {{{
     
    437413                                          ./modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.h\
    438414                                          ./modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp\
    439                                           ./modules/CostFunctionx/CostFunctionx.h\
    440                                           ./modules/CostFunctionx/CostFunctionx.cpp\
    441415                                          ./modules/Orthx/Orthx.h\
    442416                                          ./modules/Orthx/Orthx.cpp\
     
    445419                                          ./modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp\
    446420                                          ./modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h\
    447                                           ./modules/ThicknessAbsGradientx/ThicknessAbsGradientx.cpp\
    448                                           ./modules/ThicknessAbsGradientx/ThicknessAbsGradientx.h\
    449421                                          ./modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp\
    450422                                          ./modules/ThicknessAlongGradientx/ThicknessAlongGradientx.h\
     
    505477                                                ./solutions/balancethickness_core.cpp
    506478#}}}
    507 #Responses sources  {{{
    508 responses_sources = ./modules/MinVelx/MinVelx.h\
    509                                              ./modules/MinVelx/MinVelx.cpp\
    510                                              ./modules/MaxVelx/MaxVelx.h\
    511                                              ./modules/MaxVelx/MaxVelx.cpp\
    512                                              ./modules/MaxAbsVxx/MaxAbsVxx.h\
    513                                              ./modules/MaxAbsVxx/MaxAbsVxx.cpp\
    514                                              ./modules/MaxAbsVyx/MaxAbsVyx.h\
    515                                              ./modules/MaxAbsVyx/MaxAbsVyx.cpp\
    516                                              ./modules/MaxAbsVzx/MaxAbsVzx.h\
    517                                              ./modules/MaxAbsVzx/MaxAbsVzx.cpp\
    518                                              ./modules/MaxVxx/MaxVxx.h\
    519                                              ./modules/MaxVxx/MaxVxx.cpp\
    520                                              ./modules/MaxVyx/MaxVyx.h\
    521                                              ./modules/MaxVyx/MaxVyx.cpp\
    522                                              ./modules/MaxVzx/MaxVzx.h\
    523                                              ./modules/MaxVzx/MaxVzx.cpp\
    524                                              ./modules/MinVxx/MinVxx.h\
    525                                              ./modules/MinVxx/MinVxx.cpp\
    526                                              ./modules/MinVyx/MinVyx.h\
    527                                              ./modules/MinVyx/MinVyx.cpp\
    528                                              ./modules/MinVzx/MinVzx.h\
    529                                              ./modules/MinVzx/MinVzx.cpp\
    530                                              ./modules/TotalSmbx/TotalSmbx.h\
    531                                              ./modules/TotalSmbx/TotalSmbx.cpp\
    532                                              ./modules/IceVolumex/IceVolumex.h\
    533                                              ./modules/IceVolumex/IceVolumex.cpp\
    534                                              ./modules/ElementResponsex/ElementResponsex.h\
    535                                              ./modules/ElementResponsex/ElementResponsex.cpp\
    536                                              ./modules/MassFluxx/MassFluxx.cpp\
    537                                              ./modules/MassFluxx/MassFluxx.h
    538 #}}}
    539479#Slope sources  {{{
    540480slope_sources =  ./modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp\
     
    557497                                    ./classes/objects/Loads/Riftfront.h\
    558498                                    ./modules/ConstraintsStatex/RiftConstraintsState.cpp
     499#}}}
     500#Android sources  {{{
     501android_sources = ./android/fac.h\
     502                                  ./android/fac.cpp
    559503#}}}
    560504#3D sources  {{{
     
    751695                                        ./toolkits/petsc/patches/SolverEnum.h\
    752696                                        ./toolkits/petsc/patches/petscpatches.h\
    753                                         ./toolkits/petsc/patches/VecTranspose.cpp\
    754697                                        ./toolkits/petsc/patches/VecToMPISerial.cpp\
    755698                                        ./toolkits/petsc/patches/MatToSerial.cpp\
     
    759702                                        ./toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp\
    760703                                        ./toolkits/petsc/patches/NewMat.cpp\
    761                                         ./toolkits/petsc/patches/SerialToVec.cpp\
    762704                                        ./toolkits/petsc/patches/VecFree.cpp\
    763705                                        ./toolkits/petsc/patches/PetscMatrixToDoubleMatrix.cpp\
     
    765707                                        ./toolkits/petsc/patches/VecDuplicatePatch.cpp\
    766708                                        ./toolkits/petsc/patches/KSPFree.cpp\
    767                                         ./toolkits/petsc/patches/ISFree.cpp\
    768709                                        ./toolkits/petsc/patches/MatFree.cpp\
    769                                         ./toolkits/petsc/patches/GetOwnershipBoundariesFromRange.cpp\
    770                                         ./toolkits/petsc/patches/VecPartition.cpp\
    771                                         ./toolkits/petsc/patches/MatPartition.cpp\
    772                                         ./toolkits/petsc/patches/MatInvert.cpp\
    773710                                        ./toolkits/petsc/patches/MatMultPatch.cpp\
    774711                                        ./toolkits/petsc/patches/ISSMToPetscMatrixType.cpp\
     
    789726mpi_sources= ./toolkits/mpi/mpiincludes.h\
    790727                                ./toolkits/mpi/patches/mpipatches.h\
    791                                 ./toolkits/mpi/patches/DetermineLocalSize.cpp\
    792                                 ./toolkits/mpi/patches/MPI_Upperrow.cpp\
    793                                 ./toolkits/mpi/patches/MPI_Lowerrow.cpp\
    794                                 ./toolkits/mpi/patches/MPI_Boundariesfromrange.cpp
     728                                ./toolkits/mpi/patches/DetermineLocalSize.cpp
    795729#}}}
    796730#Metis sources  {{{
     
    798732                                        ./toolkits/metis/patches/METIS_PartMeshNodalPatch.cpp
    799733#}}}
    800 #Python sources  {{{
    801 python_sources=     ./python/io/pythonio.h\
    802                                         ./python/python-binding.h\
    803                                     ./python/io/WritePythonData.cpp\
    804                                     ./python/io/CheckNumPythonArguments.cpp\
    805                                     ./python/io/FetchPythonData.cpp
    806 
    807 #}}}
    808 #Matlab sources  {{{
    809 matlab_sources= ./toolkits/matlab/matlabincludes.h\
    810                                     ./matlab/matlab-binding.h\
    811                                     ./matlab/io/matlabio.h\
    812                                     ./matlab/io/MatlabNArrayToNArray.cpp\
    813                                     ./matlab/io/CheckNumMatlabArguments.cpp\
    814                                     ./matlab/io/mxGetAssignedField.cpp\
    815                                     ./matlab/io/WriteMatlabData.cpp\
    816                                     ./matlab/io/FetchMatlabData.cpp\
    817                                     ./matlab/io/OptionParse.cpp\
    818                                     ./matlab/io/MatlabMatrixToMatrix.cpp\
    819                                     ./matlab/io/MatlabVectorToVector.cpp\
    820                                          ./matlab/io/MatlabVectorToDoubleVector.cpp\
    821                                          ./matlab/io/MatlabMatrixToDoubleMatrix.cpp\
    822                                          ./matlab/io/MatlabMatrixToSeqMat.cpp\
    823                                          ./matlab/io/MatlabVectorToSeqVec.cpp
    824 #}}}
    825 #Matlab and Petsc sources  {{{
    826 matlabpetsc_sources= ./matlab/io/MatlabMatrixToPetscMat.cpp\
    827                                          ./matlab/io/MatlabVectorToPetscVec.cpp
    828 
    829 #}}}
    830734#Modules sources{{{
    831 module_sources= ./shared/Threads/issm_threads.h\
     735modules_sources= ./shared/Threads/issm_threads.h\
    832736                        ./shared/Threads/LaunchThread.cpp\
    833737                        ./shared/Threads/PartitionRange.cpp\
     
    842746                        ./shared/TriMesh/SplitMeshForRifts.cpp\
    843747                        ./shared/TriMesh/TriMeshUtils.cpp\
    844                         ./modules/AddExternalResultx/AddExternalResultx.h\
    845                         ./modules/AddExternalResultx/AddExternalResultx.cpp\
    846748                        ./modules/Chacox/Chacox.h\
    847749                        ./modules/Chacox/Chacox.cpp\
     
    853755                        ./modules/TriMeshx/TriMeshx.h\
    854756                        ./modules/TriMeshx/TriMeshx.cpp\
     757                        ./modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.h\
     758                        ./modules/TriMeshProcessRiftsx/TriMeshProcessRiftsx.cpp\
    855759                        ./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h\
    856760                        ./modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.cpp\
     
    947851endif
    948852
    949 if RESPONSES
    950 issm_sources +=  $(responses_sources)
    951 endif
    952 
    953853if SLOPE
    954854issm_sources  +=  $(slope_sources)
     
    963863endif
    964864
     865if ANDROID
     866issm_sources +=  $(android_sources)
     867endif
     868
    965869if THREED
    966870issm_sources +=  $(threed_sources)
     
    973877if METIS
    974878issm_sources +=  $(metis_sources)
    975 endif
    976 
    977 if PETSC
    978 if MATLAB
    979 issm_sources +=  $(matlabpetsc_sources)
    980 endif
    981879endif
    982880
     
    1001899endif
    1002900
    1003 if MODULES
    1004 libISSMModules_a_SOURCES = $(module_sources)
     901if WRAPPERS
     902libISSMModules_a_SOURCES = $(modules_sources)
    1005903libISSMModules_a_SOURCES += $(bamg_sources)
    1006904if KRIGING
     
    1017915endif
    1018916
    1019 if PYTHON
    1020 libISSMPython_a_SOURCES = $(python_sources)
    1021 libISSMPython_a_CXXFLAGS= $(ALLCXXFLAGS)
    1022 endif
    1023 
    1024 if MATLAB
    1025 libISSMMatlab_a_SOURCES = $(matlab_sources)
    1026 libISSMMatlab_a_CXXFLAGS= $(ALLCXXFLAGS)
    1027 if SHAREDLIBS
    1028 libISSMMatlab_la_SOURCES = $(libISSMMatlab_a_SOURCES)
    1029 endif
    1030 endif
    1031 
    1032917if VERSION
    1033918AM_LDFLAGS =
     
    1042927
    1043928#Executable {{{
     929if ANDROID
     930if ANDROIDEXE
    1044931bin_PROGRAMS = issm
     932else
     933bin_PROGRAMS =
     934endif
     935else
     936bin_PROGRAMS = issm
     937endif
    1045938
    1046939#Standard libraries
  • issm/trunk/src/c/classes/DofIndexing.cpp

    r13395 r13975  
    1010
    1111#include <stdio.h>
     12#include <string.h>
    1213#include "./classes.h"
    13 #include <string.h>
    1414#include "../EnumDefinitions/EnumDefinitions.h"
    1515#include "../shared/shared.h"
     
    2121DofIndexing::DofIndexing(){
    2222
    23         this->gsize=UNDEF;
    24         this->fsize=UNDEF;
    25         this->ssize=UNDEF;
    26         this->clone=0;
    27         this->f_set=NULL;
    28         this->s_set=NULL;
    29         this->svalues=NULL;
    30         this->doftype=NULL;
    31         this->gdoflist=NULL;
    32         this->fdoflist=NULL;
    33         this->sdoflist=NULL;
     23        this->gsize    = UNDEF;
     24        this->fsize    = UNDEF;
     25        this->ssize    = UNDEF;
     26        this->clone    = false;
     27        this->f_set    = NULL;
     28        this->s_set    = NULL;
     29        this->svalues  = NULL;
     30        this->doftype  = NULL;
     31        this->gdoflist = NULL;
     32        this->fdoflist = NULL;
     33        this->sdoflist = NULL;
    3434
    3535}
     
    4343DofIndexing::DofIndexing(DofIndexing* in){ //copy constructor
    4444
    45         int i;
    46         this->gsize=in->gsize;
    47         this->fsize=in->fsize;
    48         this->ssize=in->ssize;
    49        
    50         this->clone=in->clone;
     45        this->gsize = in->gsize;
     46        this->fsize = in->fsize;
     47        this->ssize = in->ssize;
     48        this->clone = in->clone;
    5149
    5250        if(this->gsize>0){
     
    5856        }
    5957        else{
    60                 this->f_set=NULL;
    61                 this->s_set=NULL;
    62                 this->svalues=NULL;
    63                 this->doftype=NULL;
    64                 this->gdoflist=NULL;
     58                this->f_set    = NULL;
     59                this->s_set    = NULL;
     60                this->svalues  = NULL;
     61                this->doftype  = NULL;
     62                this->gdoflist = NULL;
    6563        }
    6664        if(this->fsize>0 && this->fsize!=UNDEF)this->fdoflist=xNew<int>(this->fsize); else this->fdoflist=NULL;
     
    9593void DofIndexing::Init(int in_gsize,int* in_doftype){
    9694
    97         int i;
    9895        this->gsize=in_gsize;
    99        
    100         this->clone=0;
     96        this->clone=false;
    10197
    10298        /*allocate: */
     
    109105        }
    110106
    111         for (i=0;i<this->gsize;i++){
     107        for(int i=0;i<this->gsize;i++){
    112108                /*assume dof is free, no constraints, no rigid body constraint: */
    113109                this->f_set[i]=true;
     
    151147void DofIndexing::Echo(void){
    152148
    153         int i;
    154 
    155149        _printLine_("DofIndexing:");
    156150        _printLine_("   gsize: " << gsize);
     
    168162        _printLine_("   ssize: " << ssize);
    169163        _printLine_("   clone: " << clone);
    170        
     164
    171165        _printLine_("   set membership: f,s sets ");
    172166        for(i=0;i<gsize;i++){
     
    208202}               
    209203/*}}}*/
    210 
  • issm/trunk/src/c/classes/DofIndexing.h

    r13395 r13975  
    99
    1010class DofIndexing{
    11        
     11
    1212        public:
    1313
    1414                /*sizes: */
    15                 int gsize; //number of dofs for a node
    16                 int fsize; //number of dofs solver for
    17                 int ssize; //number of constrained dofs
     15                int gsize;   //number of dofs for a node
     16                int fsize;   //number of dofs solver for
     17                int ssize;   //number of constrained dofs
    1818
    1919                /*partitioning: */
    20                 int     clone;   //this node is replicated from another one
     20                bool clone;   //this node is replicated from another one
    2121
    2222                /*boundary conditions sets: */
    23                 bool*     f_set; //is dof on f-set (on which we solve)
    24                 bool*     s_set; //is dof on s-set (on which boundary conditions -dirichlet- are applied)
    25                 IssmDouble*   svalues; //list of constraint values. size g_size, for ease of use.
     23                bool       *f_set;    //is dof on f-set (on which we solve)
     24                bool       *s_set;    //is dof on s-set (on which boundary conditions -dirichlet- are applied)
     25                IssmDouble *svalues;  //list of constraint values. size g_size, for ease of use.
    2626
    2727                /*types of dofs: */
    28                 int*     doftype; //approximation type of the dofs (used only for coupling), size g_size
    29                
     28                int        *doftype;  //approximation type of the dofs (used only for coupling), size g_size
     29
    3030                /*list of degrees of freedom: */
    31                 int*     gdoflist; //dof list in g_set
    32                 int*     fdoflist; //dof list in f_set
    33                 int*     sdoflist; //dof list in s_set
    34 
     31                int *gdoflist;   //dof list in g_set
     32                int *fdoflist;   //dof list in f_set
     33                int *sdoflist;   //dof list in s_set
    3534
    3635                /*DofIndexing constructors, destructors {{{*/
  • issm/trunk/src/c/classes/FemModel.cpp

    r13395 r13975  
    22 * \brief: implementation of the FemModel object
    33 */
    4 
    54
    65#ifdef HAVE_CONFIG_H
     
    1312#include "../Container/Container.h"
    1413#include "../modules/ModelProcessorx/ModelProcessorx.h"
     14#include "../solutions/solutions.h"
    1515#include "../io/io.h"
    1616#include "./classes.h"
     
    2020
    2121/*Object constructors and destructor*/
    22 /*FUNCTION FemModel::constructor {{{*/
    23 FemModel::FemModel(char* rootpath, char* inputfilename, char* outputfilename, const int in_solution_type,const int* analyses,const int nummodels){
    24 
    25         /*intermediary*/
    26         int         i;
    27         int         analysis_type;
    28         FILE       *IOMODEL = NULL;
    29         extern int  my_rank;
    30 
    31         /*Open input file on cpu 0: */
    32         if(my_rank==0) IOMODEL = pfopen(inputfilename ,"rb");
    33 
    34         /*Initialize internal data: */
    35         this->nummodels=nummodels;
    36         this->solution_type=in_solution_type;
    37         this->analysis_counter=nummodels-1; //point to last analysis_type carried out.
    38         this->results=new Results(); //not initialized by CreateDataSets
     22/*FUNCTION FemModel::FemModel(int argc,char** argv){{{*/
     23FemModel::FemModel(int argc,char** argv,COMM incomm){
     24
     25        /*configuration: */
     26        int* analyses=NULL;
     27        int  numanalyses;
     28        int  solution_type;
     29        int  ierr;
     30
     31        /*File names*/
     32        char *lockfilename   = NULL;
     33        char *binfilename    = NULL;
     34        char *outbinfilename = NULL;
     35        char *petscfilename  = NULL;
     36        char *rootpath       = NULL;
     37
     38        /*First things first, store the communicator, and set it as a global variable: */
     39        this->comm=incomm;
     40        this->SetStaticComm();
    3941       
    40         /*Dynamically allocate whatever is a list of length nummodels: */
    41         analysis_type_list=xNew<int>(nummodels);
    42 
    43         /*Initialize: */
    44         for(i=0;i<nummodels;i++)analysis_type_list[i]=analyses[i];
    45 
    46         /*create datasets for all analyses*/
    47         ModelProcessorx(&this->elements,&this->nodes,&this->vertices,&this->materials,&this->constraints,&this->loads,&this->parameters,IOMODEL,rootpath,this->solution_type,nummodels,analyses);
    48 
    49         /*do the post-processing of the datasets to get an FemModel that can actually run analyses: */
    50         for(i=0;i<nummodels;i++){
    51 
    52                 if(VerboseMProcessor()) _pprintLine_("   Processing finite element model of analysis " << EnumToStringx(analysis_type_list[i]) << ":");
    53                 analysis_type=analysis_type_list[i];
    54                 this->SetCurrentConfiguration(analysis_type);
    55        
    56                 if(i==0){
    57                         if(VerboseMProcessor()) _pprintLine_("      creating vertex degrees of freedom");
    58                         VerticesDofx(vertices,parameters); //only call once, we only have one set of vertices
    59                 }
    60 
    61                 if(VerboseMProcessor()) _pprintLine_("      resolving node constraints");
    62                 SpcNodesx(nodes,constraints,parameters,analysis_type);
    63 
    64                 if(VerboseMProcessor()) _pprintLine_("      creating nodal degrees of freedom");
    65                 NodesDofx(nodes,parameters,analysis_type);
    66        
    67                 if(VerboseMProcessor()) _pprintLine_("      configuring element and loads");
    68                 ConfigureObjectsx(elements, loads, nodes, vertices, materials,parameters);
    69         }
    70        
    71         /*Close input file descriptors: */
    72         if(my_rank==0) pfclose(IOMODEL,inputfilename);
    73 
    74         /*Add output file name to parameters: */
    75         this->parameters->AddObject(new StringParam(OutputfilenameEnum,outputfilename));
    76 
    77 }
    78 
    79 /*}}}*/
    80 /*FUNCTION FemModel::destructor {{{*/
     42        /*Now, initialize PETSC: */
     43        #ifdef _HAVE_PETSC_
     44        PETSC_COMM_WORLD=this->comm;
     45        ierr=PetscInitialize(&argc,&argv,(char*)0,"");  if(ierr) _error_("Could not initialize Petsc");
     46        #endif
     47
     48        /*Start profiler: */
     49        this->profiler=new Profiler();
     50        profiler->Tag(Start);
     51
     52        /*From command line arguments, retrieve different filenames needed to create the FemModel: */
     53        ProcessArguments(&solution_type,&binfilename,&outbinfilename,&petscfilename,&lockfilename,&rootpath,argc,argv);
     54
     55        /*out of solution_type, figure out types of analyses needed in the femmodel: */
     56        AnalysisConfiguration(&analyses,&numanalyses,solution_type);
     57
     58        /*Create femmodel from input files: */
     59        profiler->Tag(StartInit);
     60        this->InitFromFiles(rootpath,binfilename,outbinfilename,petscfilename,lockfilename,solution_type,analyses,numanalyses);
     61        profiler->Tag(FinishInit);
     62
     63        /*Free resources */
     64        xDelete<int>(analyses);
     65        xDelete<char>(lockfilename);
     66        xDelete<char>(binfilename);
     67        xDelete<char>(outbinfilename);
     68        xDelete<char>(petscfilename);
     69        xDelete<char>(rootpath);
     70
     71}
     72/*}}}*/
     73/*FUNCTION FemModel::FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){{{*/
     74FemModel::FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){
     75
     76        /*Call InitFromFiles. This constructor is just a wrapper: */
     77        this->InitFromFiles(rootpath, inputfilename, outputfilename, petscfilename, lockfilename, in_solution_type,analyses,nummodels);
     78
     79}
     80/*}}}*/
     81/*FUNCTION FemModel::~FemModel{{{*/
    8182FemModel::~FemModel(){
    8283
    8384        /*Intermediary*/
    84         int i;
     85        FILE *output_fid;
     86        char *outbinfilename = NULL;
     87        char *lockfilename   = NULL;
     88        bool  waitonlock     = false;
     89
     90        /*Close output file: */
     91        this->parameters->FindParam(&output_fid,OutputFilePointerEnum);
     92        this->parameters->FindParam(&outbinfilename,OutputFileNameEnum);
     93        pfclose(output_fid,outbinfilename);
     94
     95        /*Write lock file if requested: */
     96        this->parameters->FindParam(&waitonlock,SettingsWaitonlockEnum);
     97        this->parameters->FindParam(&lockfilename,LockFileNameEnum);
     98        if (waitonlock>0){
     99                _pprintLine_("write lock file:");
     100                WriteLockFile(lockfilename);
     101        }
    85102
    86103        /*Delete all the datasets: */
    87104        xDelete<int>(analysis_type_list);
     105        xDelete<char>(outbinfilename);
     106        xDelete<char>(lockfilename);
    88107        delete elements;
    89108        delete nodes;
     
    95114        delete results;
    96115
     116        /*Before we delete the profiler, report statistics for this run: */
     117        profiler->Tag(Finish);  //final tagging
     118        _pprintLine_("");
     119        _pprintLine_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<profiler->DeltaTime(StartInit,FinishInit));
     120        _pprintLine_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<profiler->DeltaTime(StartCore,FinishCore));
     121        _pprintLine_("");
     122        _pprintLine_("   Total elapsed time:"
     123                        <<profiler->DeltaTimeModHour(Start,Finish)<<" hrs "
     124                        <<profiler->DeltaTimeModMin(Start,Finish)<<" min "
     125                        <<profiler->DeltaTimeModSec(Start,Finish)<<" sec"
     126                        );
     127        _pprintLine_("");
     128
     129        /*Now delete: */
     130        delete profiler;
     131       
     132        /*Finalize PETSC for this model: */
     133        #ifdef _HAVE_PETSC_
     134        _pprintLine_("closing Petsc");
     135        PetscFinalize();
     136        #endif
     137
    97138}
    98139/*}}}*/
     
    111152}
    112153/*}}}*/
    113 
    114 /*Numerics: */
     154/*FUNCTION FemModel::InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){{{*/
     155void FemModel::InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int in_solution_type,const int* analyses,const int nummodels){
     156
     157        /*intermediary*/
     158        int         i;
     159        int         analysis_type;
     160        FILE       *IOMODEL = NULL;
     161        FILE       *petscoptionsfid = NULL;
     162        FILE       *output_fid = NULL;
     163        int         my_rank;
     164
     165        /*recover my_rank:*/
     166        my_rank=IssmComm::GetRank();
     167
     168        /*Open input file on cpu 0: */
     169        if(my_rank==0) IOMODEL = pfopen(inputfilename ,"rb");
     170
     171        /*Initialize internal data: */
     172        this->nummodels        = nummodels;
     173        this->solution_type    = in_solution_type;
     174        this->analysis_counter = nummodels-1;   //point to last analysis_type carried out.
     175        this->results          = new Results(); //not initialized by CreateDataSets
     176
     177        /*Dynamically allocate whatever is a list of length nummodels: */
     178        analysis_type_list=xNew<int>(nummodels);
     179
     180        /*Initialize: */
     181        for(i=0;i<nummodels;i++)analysis_type_list[i]=analyses[i];
     182
     183        /*create datasets for all analyses*/
     184        ModelProcessorx(&this->elements,&this->nodes,&this->vertices,&this->materials,&this->constraints,&this->loads,&this->parameters,IOMODEL,rootpath,this->solution_type,nummodels,analyses);
     185
     186        /*do the post-processing of the datasets to get an FemModel that can actually run analyses: */
     187        for(i=0;i<nummodels;i++){
     188
     189                if(VerboseMProcessor()) _pprintLine_("   Processing finite element model of analysis " << EnumToStringx(analysis_type_list[i]) << ":");
     190                analysis_type=analysis_type_list[i];
     191                this->SetCurrentConfiguration(analysis_type);
     192
     193                if(i==0){
     194                        if(VerboseMProcessor()) _pprintLine_("      creating vertex degrees of freedom");
     195                        VerticesDofx(vertices,parameters); //only call once, we only have one set of vertices
     196                }
     197
     198                if(VerboseMProcessor()) _pprintLine_("      resolving node constraints");
     199                SpcNodesx(nodes,constraints,parameters,analysis_type);
     200
     201                if(VerboseMProcessor()) _pprintLine_("      creating nodal degrees of freedom");
     202                NodesDofx(nodes,parameters,analysis_type);
     203
     204                if(VerboseMProcessor()) _pprintLine_("      configuring element and loads");
     205                ConfigureObjectsx(elements, loads, nodes, vertices, materials,parameters);
     206        }
     207
     208        /*Close input file descriptors: */
     209        if(my_rank==0) pfclose(IOMODEL,inputfilename);
     210
     211        /*Open output file once for all and add output file name and file descriptor to parameters*/
     212        output_fid=pfopen(outputfilename,"wb");
     213        this->parameters->AddObject(new StringParam(OutputFileNameEnum,outputfilename));
     214        this->parameters->SetParam(output_fid,OutputFilePointerEnum);
     215
     216        /*Save lock file name for later: */
     217        this->parameters->AddObject(new StringParam(LockFileNameEnum,lockfilename));
     218
     219        /*Now, deal with petsc options, which need to be put into the parameters dataset: */
     220        petscoptionsfid=pfopen(petscfilename,"r");
     221        ParsePetscOptionsx(this->parameters,petscoptionsfid);
     222        pfclose(petscoptionsfid,petscfilename);
     223}
     224/*}}}*/
     225/*FUNCTION FemModel::OutputResults {{{*/
     226void FemModel::OutputResults(void){
     227
     228        _pprintLine_("write results to disk:");
     229
     230        /*Just call the OutputResultsx module: */
     231        OutputResultsx(this->elements, this->nodes, this->vertices, this->loads, this->materials, this->parameters,this->results);
     232
     233}
     234/*}}}*/
     235/*FUNCTION FemModel::SetStaticComm {{{*/
     236void FemModel::SetStaticComm(void){
     237
     238        /*This routine sets the global communicator variable hidden inside the IssmComm
     239         *class: */
     240        IssmComm::SetComm(this->comm);
     241
     242}
     243/*}}}*/
    115244/*FUNCTION FemModel::SetCurrentConfiguration(int configuration_type,int analysis_type){{{*/
    116245void FemModel::SetCurrentConfiguration(int configuration_type,int analysis_type){
     
    153282/*FUNCTION FemModel::SetCurrentConfiguration(int configuration_type){{{*/
    154283void FemModel::SetCurrentConfiguration(int configuration_type){
    155 
    156         /*overload: analysis_type = configuration_type: */
    157284        this->SetCurrentConfiguration(configuration_type,configuration_type);
    158285}
    159286/*}}}*/
     287/*FUNCTION FemModel::Solve {{{*/
     288void FemModel::Solve(void){
     289
     290        /*profiling: */
     291        bool profiling = false;
     292        IssmDouble solution_time;
     293        IssmDouble solution_flops;
     294        IssmDouble solution_memory;
     295
     296        /*solution: */
     297        int solution_type;
     298        void (*solutioncore)(FemModel*)=NULL; //core solution function pointer
     299
     300        _pprintLine_("call computational core:");
     301
     302        /*Retrieve solution_type from parameters: */
     303        parameters->FindParam(&solution_type,SolutionTypeEnum);
     304
     305        /*Figure out which solution core we are going to run with the current solution type: */
     306        WrapperCorePointerFromSolutionEnum(&solutioncore,this->parameters,solution_type);
     307
     308        /*run solutoin core: */
     309        profiler->Tag(StartCore);   
     310        solutioncore(this);
     311        profiler->Tag(FinishCore);
     312
     313        /*run AD core if needed: */
     314        profiler->Tag(StartAdCore);
     315        ad_core(this);     
     316        profiler->Tag(FinishAdCore);
     317
     318        /*some profiling results for the core: */
     319        parameters->FindParam(&profiling,DebugProfilingEnum);
     320        if(profiling){
     321
     322                solution_time=profiler->DeltaTime(StartCore,FinishCore);
     323                solution_flops=profiler->DeltaFlops(StartCore,FinishCore);
     324                solution_memory=profiler->Memory(FinishCore);
     325
     326                _pprintLine_("Solution elapsed time  : " << solution_time << "  Seconds");
     327                _pprintLine_("Solution elapsed flops : " << solution_flops << "  Flops");
     328                _pprintLine_("Solution memory used   : " << solution_memory << "  Bytes");
     329
     330                /*Add to results: */
     331                results->AddObject(new GenericExternalResult<IssmDouble>(results->Size()+1, ProfilingSolutionTimeEnum, solution_time, 1, 0));
     332                results->AddObject(new GenericExternalResult<IssmDouble>(results->Size()+1, ProfilingCurrentMemEnum, solution_memory, 1, 0));
     333                results->AddObject(new GenericExternalResult<IssmDouble>(results->Size()+1, ProfilingCurrentFlopsEnum, solution_flops, 1, 0));
     334        }
     335}
     336/*}}}*/
     337
     338/*Modules:*/
     339void FemModel::AllocateSystemMatrices(Matrix<IssmDouble>** pKff,Matrix<IssmDouble>** pKfs,Vector<IssmDouble>** pdf,Vector<IssmDouble>** ppf){ /*{{{*/
     340
     341        /*Intermediary*/
     342        int  fsize,ssize,flocalsize,slocalsize;
     343        int  connectivity, numberofdofspernode;
     344        int  configuration_type;
     345        int  m,n,M,N;
     346        int *d_nnz = NULL;
     347        int *o_nnz = NULL;
     348
     349        /*output*/
     350        Matrix<IssmDouble> *Kff  = NULL;
     351        Matrix<IssmDouble> *Kfs  = NULL;
     352        Vector<IssmDouble> *pf   = NULL;
     353        Vector<IssmDouble> *df   = NULL;
     354
     355        bool oldalloc=false;
     356
     357        /*retrieve parameters: */
     358        this->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
     359        this->parameters->FindParam(&connectivity,MeshAverageVertexConnectivityEnum);
     360
     361        /*retrieve node info*/
     362        fsize      = this->nodes->NumberOfDofs(configuration_type,FsetEnum);
     363        ssize      = this->nodes->NumberOfDofs(configuration_type,SsetEnum);
     364        flocalsize = this->nodes->NumberOfDofsLocal(configuration_type,FsetEnum);
     365        slocalsize = this->nodes->NumberOfDofsLocal(configuration_type,SsetEnum);
     366
     367        numberofdofspernode=this->nodes->MaxNumDofs(configuration_type,GsetEnum);
     368
     369        if(oldalloc){
     370                if(pKff) Kff=new Matrix<IssmDouble>(fsize,fsize,connectivity,numberofdofspernode);
     371                if(pKfs) Kfs=new Matrix<IssmDouble>(fsize,ssize,connectivity,numberofdofspernode);
     372                if(pdf)  df =new Vector<IssmDouble>(fsize);
     373                if(ppf)  pf =new Vector<IssmDouble>(fsize);
     374        }
     375        else{
     376                if(pKff){
     377                        m=flocalsize; n=flocalsize; /*local  sizes*/
     378                        M=fsize;      N=fsize;      /*global sizes*/
     379                        this->MatrixNonzeros(&d_nnz,&o_nnz,FsetEnum,FsetEnum);
     380                        Kff=new Matrix<IssmDouble>(m,n,M,N,d_nnz,o_nnz);
     381                        xDelete<int>(d_nnz);
     382                        xDelete<int>(o_nnz);
     383                }
     384                if(pKfs){
     385                        m=flocalsize; n=slocalsize; /*local  sizes*/
     386                        M=fsize;      N=ssize;      /*global sizes*/
     387                        this->MatrixNonzeros(&d_nnz,&o_nnz,FsetEnum,SsetEnum);
     388                        Kfs=new Matrix<IssmDouble>(m,n,M,N,d_nnz,o_nnz);
     389                        xDelete<int>(d_nnz);
     390                        xDelete<int>(o_nnz);
     391                }
     392                if(pdf) df =new Vector<IssmDouble>(flocalsize,fsize);
     393                if(ppf) pf =new Vector<IssmDouble>(flocalsize,fsize);
     394        }
     395
     396        /*Allocate output pointers*/
     397        if(pKff) *pKff = Kff;
     398        if(pKfs) *pKfs = Kfs;
     399        if(pdf)  *pdf  = df;
     400        if(ppf)  *ppf  = pf;
     401}
     402/*}}}*/
     403void FemModel::MatrixNonzeros(int** pd_nnz,int** po_nnz,int set1enum,int set2enum){/*{{{*/
     404
     405        /*Intermediary*/
     406        int      i,j,k,index,offset,count;
     407        int      configuration_type;
     408        int      d_nz,o_nz;
     409        Element *element            = NULL;
     410        Load    *load               = NULL;
     411        int     *head_e             = NULL;
     412        int     *next_e             = NULL;
     413        int     *count2offset_e     = NULL;
     414        int     *head_l             = NULL;
     415        int     *next_l             = NULL;
     416        int     *count2offset_l     = NULL;
     417        int     *sidlist            = NULL;
     418
     419        /*output*/
     420        int *d_nnz = NULL;
     421        int *o_nnz = NULL;
     422
     423        /*retrive parameters: */
     424        this->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
     425
     426        /*Get vector size and number of nodes*/
     427        int numnodes            = nodes->NumberOfNodes(configuration_type);
     428        int numberofdofspernode = nodes->MaxNumDofs(configuration_type,GsetEnum);
     429        int M                   = nodes->NumberOfDofs(configuration_type,set1enum);
     430        int N                   = nodes->NumberOfDofs(configuration_type,set2enum);
     431        int m                   = nodes->NumberOfDofsLocal(configuration_type,set1enum);
     432        int n                   = nodes->NumberOfDofsLocal(configuration_type,set2enum);
     433        int numnodesperelement  = elements->MaxNumNodes();
     434        int numnodesperload     = loads->MaxNumNodes(configuration_type);
     435
     436        /*First, we are building chaining vectors so that we know what nodes are
     437         * connected to what elements. These vectors are such that:
     438         *   for(int i=head[id];i!=-1;i=next[i])
     439         * will loop over all the elements that are connected to the node number
     440         * id*/
     441        head_e         = xNew<int>(numnodes); for(i=0;i<numnodes;i++) head_e[i]=-1;
     442        next_e         = xNew<int>(elements->Size()*numnodesperelement);
     443        count2offset_e = xNew<int>(elements->Size()*numnodesperelement);
     444
     445        k=0;
     446        for(i=0;i<elements->Size();i++){
     447                element = dynamic_cast<Element*>(elements->GetObjectByOffset(i));
     448                sidlist = xNew<int>(element->GetNumberOfNodes());
     449                element->GetNodesSidList(sidlist);
     450
     451                for(j=0;j<element->GetNumberOfNodes();j++){
     452                        index = sidlist[j];
     453                        _assert_(index>=0 && index<numnodes);
     454
     455                        count2offset_e[k]=i;
     456                        next_e[k]=head_e[index];
     457                        head_e[index]=k++;
     458                }
     459                for(j=0;j<numnodesperelement-element->GetNumberOfNodes();j++) k++;
     460
     461                xDelete<int>(sidlist);
     462        }
     463
     464        /*Chain for loads*/
     465        head_l         = xNew<int>(numnodes); for(i=0;i<numnodes;i++) head_l[i]=-1;
     466        next_l         = xNew<int>(loads->Size(configuration_type)*numnodesperload);
     467        count2offset_l = xNew<int>(loads->Size(configuration_type)*numnodesperload);
     468        k=0;
     469        for(i=0;i<loads->Size();i++){
     470                load = dynamic_cast<Load*>(loads->GetObjectByOffset(i));
     471                if(!load->InAnalysis(configuration_type)) continue;
     472                sidlist = xNew<int>(load->GetNumberOfNodes());
     473                load->GetNodesSidList(sidlist);
     474
     475                for(j=0;j<load->GetNumberOfNodes();j++){
     476                        index = sidlist[j];
     477                        _assert_(index>=0 && index<numnodes);
     478
     479                        count2offset_l[k]=i;
     480                        next_l[k]=head_l[index];
     481                        head_l[index]=k++;
     482                }
     483                for(j=0;j<numnodesperload-load->GetNumberOfNodes();j++) k++;
     484
     485                xDelete<int>(sidlist);
     486        }
     487
     488        /*OK now count number of dofs and flag each nodes for each node i*/
     489        bool *flags                  = xNew<bool>(numnodes);
     490        int  *d_connectivity         = xNewZeroInit<int>(numnodes);
     491        int  *o_connectivity         = xNewZeroInit<int>(numnodes);
     492        int  *connectivity_clone     = xNewZeroInit<int>(numnodes);
     493        int  *all_connectivity_clone = xNewZeroInit<int>(numnodes);
     494
     495        /*Create connectivity vector*/
     496        for(i=0;i<nodes->Size();i++){
     497                Node* node=dynamic_cast<Node*>(nodes->GetObjectByOffset(i));
     498                if(node->InAnalysis(configuration_type)){
     499
     500                        /*Reinitialize flags to 0*/
     501                        for(j=0;j<numnodes;j++) flags[j]=false;
     502
     503                        /*Loop over elements that hold node number i*/
     504                        _assert_(head_e[node->Sid()]!=-1 || head_l[node->Sid()]!=-1);
     505                        for(j=head_e[node->Sid()];j!=-1;j=next_e[j]){
     506                                offset=count2offset_e[j];
     507                                element=dynamic_cast<Element*>(elements->GetObjectByOffset(offset));
     508                                element->SetwiseNodeConnectivity(&d_nz,&o_nz,node,flags,set1enum,set2enum);
     509                                if(node->IsClone()){
     510                                        connectivity_clone[node->Sid()]+=d_nz+o_nz;
     511                                }
     512                                else{
     513                                        d_connectivity[node->Sid()]+=d_nz;
     514                                        o_connectivity[node->Sid()]+=o_nz;
     515                                }
     516                        }
     517                        for(j=head_l[node->Sid()];j!=-1;j=next_l[j]){
     518                                offset=count2offset_l[j];
     519                                load=dynamic_cast<Load*>(loads->GetObjectByOffset(offset));
     520                                load->SetwiseNodeConnectivity(&d_nz,&o_nz,node,flags,set1enum,set2enum);
     521                                if(node->IsClone()){
     522                                        connectivity_clone[node->Sid()]+=d_nz+o_nz;
     523                                }
     524                                else{
     525                                        d_connectivity[node->Sid()]+=d_nz;
     526                                        o_connectivity[node->Sid()]+=o_nz;
     527                                }
     528                        }
     529                }
     530        }
     531        xDelete<bool>(flags);
     532        xDelete<int>(count2offset_e);
     533        xDelete<int>(head_e);
     534        xDelete<int>(next_e);
     535        xDelete<int>(count2offset_l);
     536        xDelete<int>(head_l);
     537        xDelete<int>(next_l);
     538
     539        /*sum over all cpus*/
     540#ifdef _HAVE_MPI_
     541        MPI_Allreduce((void*)connectivity_clone,(void*)all_connectivity_clone,numnodes,MPI_INT,MPI_SUM,IssmComm::GetComm());
     542#endif
     543        xDelete<int>(connectivity_clone);
     544
     545        if(set1enum==FsetEnum){
     546                count=0;
     547                d_nnz=xNew<int>(m);
     548                o_nnz=xNew<int>(m);
     549                for(i=0;i<nodes->Size();i++){
     550                        Node* node=dynamic_cast<Node*>(nodes->GetObjectByOffset(i));
     551                        if(node->InAnalysis(configuration_type) && !node->IsClone()){
     552                                for(j=0;j<node->indexing.fsize;j++){
     553                                        _assert_(count<m);
     554                                        d_nnz[count]=numberofdofspernode*(d_connectivity[node->Sid()] + all_connectivity_clone[node->Sid()]);
     555                                        o_nnz[count]=numberofdofspernode*(o_connectivity[node->Sid()] + all_connectivity_clone[node->Sid()]);
     556                                        if(d_nnz[count]>n)   d_nnz[count]=n;
     557                                        if(o_nnz[count]>N-n) o_nnz[count]=N-n;
     558                                        count++;
     559                                }
     560                        }
     561                }
     562                _assert_(m==count);
     563        }
     564        else{
     565                _error_("STOP not implemented");
     566        }
     567        xDelete<int>(d_connectivity);
     568        xDelete<int>(o_connectivity);
     569        xDelete<int>(all_connectivity_clone);
     570
     571        /*Allocate ouptput pointer*/
     572        *pd_nnz=d_nnz;
     573        *po_nnz=o_nnz;
     574
     575}/*}}}*/
     576void FemModel::CreateJacobianMatrixx(Matrix<IssmDouble>** pJff,IssmDouble kmax){/*{{{*/
     577
     578        int      i,connectivity;
     579        int      numberofdofspernode;
     580        int      fsize,configuration_type;
     581        Element *element = NULL;
     582        Load    *load    = NULL;
     583        Matrix<IssmDouble>* Jff = NULL;
     584
     585        /*Checks*/
     586        _assert_(nodes && elements);
     587
     588        /*Recover some parameters*/
     589        parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
     590        parameters->FindParam(&connectivity,MeshAverageVertexConnectivityEnum);
     591        fsize=nodes->NumberOfDofs(configuration_type,FsetEnum);
     592        numberofdofspernode=nodes->MaxNumDofs(configuration_type,GsetEnum);
     593
     594        /*Initialize Jacobian Matrix*/
     595        this->AllocateSystemMatrices(&Jff,NULL,NULL,NULL);
     596
     597        /*Create and assemble matrix*/
     598        for(i=0;i<elements->Size();i++){
     599                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
     600                element->CreateJacobianMatrix(Jff);
     601        }
     602        for (i=0;i<loads->Size();i++){
     603                load=(Load*)loads->GetObjectByOffset(i);
     604                if(load->InAnalysis(configuration_type)) load->CreateJacobianMatrix(Jff);
     605                if(load->InAnalysis(configuration_type)) load->PenaltyCreateJacobianMatrix(Jff,kmax);
     606        }
     607        Jff->Assemble();
     608
     609        /*Assign output pointer*/
     610        *pJff=Jff;
     611
     612}/*}}}*/
     613int  FemModel::UpdateVertexPositionsx(void){ /*{{{*/
     614
     615        int     i;
     616        Vector<IssmDouble>*     vz        = NULL;
     617        Vertex *vertex    = NULL;
     618        IssmDouble *thickness = NULL;
     619        IssmDouble *bed       = NULL;
     620
     621        /*get vertex vectors for bed and thickness: */
     622        GetVectorFromInputsx(&thickness,elements,nodes, vertices, loads, materials, parameters, ThicknessEnum,VertexEnum);
     623        GetVectorFromInputsx(&bed      ,elements,nodes, vertices, loads, materials, parameters, BedEnum,      VertexEnum);
     624
     625        /*Allocate vector*/
     626        vz=new Vector<IssmDouble>(vertices->NumberOfVertices());
     627
     628        /*Update verices new geometry: */
     629        for (i=0;i<vertices->Size();i++){
     630                vertex=(Vertex*)vertices->GetObjectByOffset(i);
     631                vertex->UpdatePosition(vz,parameters,thickness,bed);
     632        }
     633
     634        /*Assemble mesh velocity*/
     635        vz->Assemble();
     636
     637        /*Update element inputs*/
     638        InputUpdateFromVectorx(elements,nodes,vertices,loads,materials,parameters,vz,VzMeshEnum,VertexEnum);
     639
     640        /*Free ressources:*/
     641        xDelete<IssmDouble>(thickness);
     642        xDelete<IssmDouble>(bed);
     643        xdelete(&vz);
     644        return 1;
     645}
     646/*}}}*/
     647void FemModel::UpdateConstraintsx(void){ /*{{{*/
     648
     649        IssmDouble time;
     650        int    analysis_type;
     651
     652        /*retrieve parameters: */
     653        parameters->FindParam(&analysis_type,AnalysisTypeEnum);
     654        parameters->FindParam(&time,TimeEnum);
     655
     656        /*start module: */
     657        if(VerboseModule()) _pprintLine_("   Updating constraints for time: " << time);
     658
     659        /*First, update dof constraints in nodes, using constraints: */
     660        SpcNodesx(nodes,constraints,parameters,analysis_type);
     661
     662        /*Now, update degrees of freedoms: */
     663        NodesDofx(nodes,parameters,analysis_type);
     664
     665}
     666/*}}}*/
     667void FemModel::Responsex(IssmDouble* responses,const char* response_descriptor,bool process_units,int weight_index){/*{{{*/
     668
     669        int response_descriptor_enum=StringToEnumx(response_descriptor);
     670        this->Responsex(responses, response_descriptor_enum, process_units, weight_index);
     671
     672}
     673/*}}}*/
     674void FemModel::Responsex(IssmDouble* responses,int response_descriptor_enum,bool process_units,int weight_index){/*{{{*/
     675
     676
     677        switch (response_descriptor_enum){
     678
     679                #ifdef _HAVE_RESPONSES_
     680                case IceVolumeEnum:              this->IceVolumex(responses,process_units); break;
     681                case MinVelEnum:                 this->MinVelx(responses,process_units); break;
     682                case MaxVelEnum:                 this->MaxVelx(                  responses,process_units); break;
     683                case MinVxEnum:                  this->MinVxx(responses,process_units); break;
     684                case MaxVxEnum:                  this->MaxVxx(                   responses,process_units); break;
     685                case MaxAbsVxEnum:               this->MaxAbsVxx(                responses,process_units); break;
     686                case MinVyEnum:                  this->MinVyx(responses,process_units); break;
     687                case MaxVyEnum:                  this->MaxVyx(                   responses,process_units); break;
     688                case MaxAbsVyEnum:               this->MaxAbsVyx(                responses,process_units); break;
     689                case MinVzEnum:                  this->MinVzx(responses,process_units); break;
     690                case MaxVzEnum:                  this->MaxVzx(                   responses,process_units); break;
     691                case MaxAbsVzEnum:               this->MaxAbsVzx(                responses,process_units); break;
     692                case MassFluxEnum:               this->MassFluxx(         responses,process_units); break;
     693                case SurfaceAbsVelMisfitEnum:    SurfaceAbsVelMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
     694                case SurfaceRelVelMisfitEnum:    SurfaceRelVelMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
     695                case SurfaceLogVelMisfitEnum:    SurfaceLogVelMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
     696                case SurfaceLogVxVyMisfitEnum:   SurfaceLogVxVyMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
     697                case SurfaceAverageVelMisfitEnum:SurfaceAverageVelMisfitx( responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
     698                case ThicknessAbsMisfitEnum:     ThicknessAbsMisfitx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
     699                case ThicknessAbsGradientEnum:   this->ThicknessAbsGradientx(responses, process_units,weight_index); break;
     700                case ThicknessAlongGradientEnum: ThicknessAlongGradientx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
     701                case ThicknessAcrossGradientEnum:ThicknessAcrossGradientx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
     702                case TotalSmbEnum:                                      this->TotalSmbx(responses,process_units); break;
     703                case RheologyBbarAbsGradientEnum:RheologyBbarAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
     704                case DragCoefficientAbsGradientEnum:DragCoefficientAbsGradientx(responses, elements,nodes, vertices, loads, materials, parameters,process_units,weight_index); break;
     705                case MaterialsRheologyBbarEnum: this->ElementResponsex(responses,MaterialsRheologyBbarEnum,process_units); break;
     706                case VelEnum:                   this->ElementResponsex(responses,VelEnum,process_units); break;
     707                case FrictionCoefficientEnum:NodalValuex(responses, FrictionCoefficientEnum,elements,nodes, vertices, loads, materials, parameters,process_units); break;
     708                default: _error_("response descriptor \"" << EnumToStringx(response_descriptor_enum) << "\" not supported yet!"); break;
     709                #else
     710                default: _error_("ISSM was not compiled with responses capabilities, exiting!");
     711                #endif
     712        }
     713
     714}
     715/*}}}*/
     716void FemModel::RequestedOutputsx(int* requested_outputs, int numoutputs){/*{{{*/
     717
     718
     719        int      output_enum;
     720        int      step;
     721        IssmDouble   time;
     722        IssmDouble   output_value;
     723        Element *element      = NULL;
     724
     725        /*Get time and step*/
     726        parameters->FindParam(&step,StepEnum);
     727        parameters->FindParam(&time,TimeEnum);
     728
     729        /*retrieve Inputs*/
     730        if(numoutputs){
     731                for(int i=0;i<numoutputs;i++){
     732                        output_enum=requested_outputs[i];
     733
     734                        switch(output_enum){
     735
     736                                case IceVolumeEnum:
     737                                        Responsex(&output_value,"IceVolume",false,0);
     738                                        results->AddObject(new GenericExternalResult<double>(results->Size()+1,IceVolumeEnum,reCast<IssmPDouble>(output_value),step,time));
     739                                        break;
     740                                case TotalSmbEnum:
     741                                        Responsex(&output_value,"TotalSmb",false,0);
     742                                        results->AddObject(new GenericExternalResult<double>(results->Size()+1,TotalSmbEnum,reCast<IssmPDouble>(output_value),step,time));
     743                                        break;
     744                                case MaxVelEnum:
     745                                        Responsex(&output_value,"MaxVel",false,0);
     746                                        results->AddObject(new GenericExternalResult<double>(results->Size()+1,MaxVelEnum,reCast<IssmPDouble>(output_value),step,time));
     747                                        break;
     748                                default:
     749                                        /*create this output in the element inputs, and then transfer to results:*/
     750                                        for(int j=0;j<elements->Size();j++){
     751                                                element=(Element*)elements->GetObjectByOffset(j);
     752                                                element->RequestedOutput(output_enum,step,time);
     753                                        }
     754                                        break;
     755                        }
     756                }
     757        }
     758}
     759/*}}}*/
     760void FemModel::RequestedDependentsx(void){/*{{{*/
     761
     762
     763        bool        isautodiff      = false;
     764        IssmDouble  output_value;
     765
     766        int         num_dependents;
     767        IssmPDouble *dependents;
     768        DataSet*    dependent_objects=NULL;
     769
     770        /*AD mode on?: */
     771        parameters->FindParam(&isautodiff,AutodiffIsautodiffEnum);
     772
     773        if(isautodiff){
     774                #ifdef _HAVE_ADOLC_
     775                parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
     776                parameters->FindParam(&dependent_objects,AutodiffDependentObjectsEnum);
     777                if(num_dependents){
     778                        dependents=xNew<IssmPDouble>(num_dependents);
     779
     780                        /*Go through our dependent variables, and compute the response:*/
     781                        for(int i=0;i<dependent_objects->Size();i++){
     782                                DependentObject* dep=(DependentObject*)dependent_objects->GetObjectByOffset(i);
     783                                dep->Responsex(&output_value,this);
     784                                output_value>>=dependents[i];
     785                        }
     786                }
     787                delete dependent_objects;
     788                #else
     789                _error_("Should not be requesting dependents when an AD library is not available!");
     790                #endif
     791        }
     792}
     793/*}}}*/
     794void FemModel::SystemMatricesx(Matrix<IssmDouble>** pKff, Matrix<IssmDouble>** pKfs, Vector<IssmDouble>** ppf, Vector<IssmDouble>** pdf, IssmDouble* pkmax){/*{{{*/
     795
     796        /*intermediary: */
     797        int      i;
     798        int      configuration_type;
     799        Element *element = NULL;
     800        Load    *load    = NULL;
     801
     802        /*output: */
     803        Matrix<IssmDouble> *Kff  = NULL;
     804        Matrix<IssmDouble> *Kfs  = NULL;
     805        Vector<IssmDouble> *pf   = NULL;
     806        Vector<IssmDouble> *df   = NULL;
     807        IssmDouble          kmax = 0;
     808
     809        /*Display message*/
     810        if(VerboseModule()) _pprintLine_("   Generating matrices");
     811
     812        /*retrive parameters: */
     813        this->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
     814
     815        /*First, we might need to do a dry run to get kmax if penalties are employed*/
     816        if(loads->IsPenalty(configuration_type)){
     817
     818                /*Allocate Kff_temp*/
     819                Matrix<IssmDouble> *Kff_temp = NULL;
     820                this->AllocateSystemMatrices(&Kff_temp,NULL,NULL,NULL);
     821
     822                /*Get complete stiffness matrix without penalties*/
     823                for (i=0;i<this->elements->Size();i++){
     824                        element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
     825                        element->CreateKMatrix(Kff_temp,NULL,NULL);
     826                }
     827                for (i=0;i<this->loads->Size();i++){
     828                        load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
     829                        if(load->InAnalysis(configuration_type)) load->CreateKMatrix(Kff_temp,NULL);
     830                }
     831                Kff_temp->Assemble();
     832
     833                /*Now, figure out maximum value of stiffness matrix, so that we can penalize it correctly: */
     834                kmax=Kff_temp->Norm(NORM_INF);
     835                delete Kff_temp;
     836        }
     837
     838        /*Allocate stiffness matrices and load vector*/
     839        this->AllocateSystemMatrices(&Kff,&Kfs,&df,&pf);
     840
     841        /*Fill stiffness matrix from elements and loads */
     842        for (i=0;i<this->elements->Size();i++){
     843                element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
     844                element->CreateKMatrix(Kff,Kfs,df);
     845        }
     846        for (i=0;i<this->loads->Size();i++){
     847                load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
     848                if(load->InAnalysis(configuration_type)) load->CreateKMatrix(Kff,Kfs);
     849        }
     850
     851        /*Fill right hand side vector, from elements and loads */
     852        for (i=0;i<this->elements->Size();i++){
     853                element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
     854                element->CreatePVector(pf);
     855        }
     856        for (i=0;i<this->loads->Size();i++){
     857                load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
     858                if(load->InAnalysis(configuration_type)) load->CreatePVector(pf);
     859        }
     860
     861        /*Now deal with penalties (only in loads)*/
     862        if(loads->IsPenalty(configuration_type)){
     863                for (i=0;i<this->loads->Size();i++){
     864                        load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
     865                        if(load->InAnalysis(configuration_type)) load->PenaltyCreateKMatrix(Kff,Kfs,kmax);
     866                }
     867                for (i=0;i<this->loads->Size();i++){
     868                        load=dynamic_cast<Load*>(this->loads->GetObjectByOffset(i));
     869                        if(load->InAnalysis(configuration_type)) load->PenaltyCreatePVector(pf,kmax);
     870                }
     871        }
     872
     873        /*Assemble matrices and vector*/
     874        Kff->Assemble();
     875        Kfs->Assemble();
     876        pf->Assemble();
     877        df->Assemble();
     878        //Kff->AllocationInfo();
     879        //Kfs->AllocationInfo();
     880
     881        /*Assign output pointers: */
     882        if(pKff) *pKff=Kff;
     883        else      xdelete(&Kff);
     884        if(pKfs) *pKfs=Kfs;
     885        else      xdelete(&Kfs);
     886        if(ppf)  *ppf=pf;
     887        else      xdelete(&pf);
     888        if(pdf)  *pdf=df;
     889        else      xdelete(&df);
     890        if(pkmax) *pkmax=kmax;
     891}
     892/*}}}*/
     893void FemModel::TimeAdaptx(IssmDouble* pdt){/*{{{*/
     894
     895        int      i;
     896
     897        /*output: */
     898        IssmDouble   dt;
     899
     900        /*intermediary: */
     901        Element *element     = NULL;
     902        IssmDouble   min_dt      = 0;
     903        IssmDouble   node_min_dt = 0;
     904
     905        /*Go through elements, and figure out the minimum of the time steps for each element (using CFL criterion): */
     906        element=(Element*)elements->GetObjectByOffset(0); min_dt=element->TimeAdapt();
     907
     908        for (i=1;i<elements->Size();i++){
     909                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
     910                dt=element->TimeAdapt();
     911                if(dt<min_dt)min_dt=dt;
     912        }
     913
     914        /*Figure out minimum across the cluster: */
     915#ifdef _HAVE_MPI_
     916        MPI_Reduce (&min_dt,&node_min_dt,1,MPI_DOUBLE,MPI_MIN,0,IssmComm::GetComm() );
     917        MPI_Bcast(&node_min_dt,1,MPI_DOUBLE,0,IssmComm::GetComm());
     918        min_dt=node_min_dt;
     919#endif
     920
     921        /*Assign output pointers:*/
     922        *pdt=min_dt;
     923}
     924/*}}}*/
     925#ifdef _HAVE_RESPONSES_
     926void FemModel::MassFluxx(IssmDouble* pmass_flux,bool process_units){/*{{{*/
     927
     928        int          i,j;
     929        Element     *element       = NULL;
     930        int          element_id;
     931        bool         ispresent     = false;
     932        IssmDouble   mass_flux     = 0;
     933        IssmDouble   all_mass_flux = 0;
     934        int          counter;
     935        IssmDouble **array         = NULL;
     936        int          M;
     937        int         *mdims_array   = NULL;
     938        int         *ndims_array   = NULL;
     939        IssmDouble  *segments      = NULL;
     940        int          num_segments;
     941
     942        /*First, figure out which segment to compute our mass flux on. Start with retrieving qmu_mass_flux_segments: */
     943        this->parameters->FindParam(&ispresent,MassFluxSegmentsPresentEnum);
     944        if(!ispresent)_error_("no mass flux segments available!");
     945        this->parameters->FindParam(&array,&M,&mdims_array,&ndims_array,MassFluxSegmentsEnum);
     946
     947        /*Retrieve index of segments being used for MassFlux computation: */
     948        parameters->FindParam(&counter,IndexEnum);
     949
     950        /*retrieve segments from array: */
     951        segments     = array[counter-1]; //matlab to "C" indexing
     952        num_segments = mdims_array[counter-1];
     953
     954        /*Go through segments, and then elements, and figure out which elements belong to a segment.
     955         * When we find one, use the element to compute the mass flux on the segment: */
     956        for(i=0;i<num_segments;i++){
     957                element_id=reCast<int,IssmDouble>(*(segments+5*i+4));
     958                for(j=0;j<elements->Size();j++){
     959                        element=(Element*)this->elements->GetObjectByOffset(j);
     960                        if (element->Id()==element_id){
     961                                /*We found the element which owns this segment, use it to compute the mass flux: */
     962                                mass_flux+=element->MassFlux(segments+5*i+0,process_units);
     963                                break;
     964                        }
     965                }
     966        }
     967
     968#ifdef _HAVE_MPI_
     969        MPI_Allreduce ( (void*)&mass_flux,(void*)&all_mass_flux,1,MPI_DOUBLE,MPI_SUM,IssmComm::GetComm());
     970        mass_flux=all_mass_flux;
     971#endif
     972
     973        /*Free ressources:*/
     974        for(i=0;i<M;i++){
     975                IssmDouble* matrix=array[i];
     976                xDelete<IssmDouble>(matrix);
     977        }
     978        xDelete<int>(mdims_array);
     979        xDelete<int>(ndims_array);
     980        xDelete<IssmDouble*>(array);
     981
     982        /*Assign output pointers: */
     983        *pmass_flux=mass_flux;
     984
     985}/*}}}*/
     986void FemModel::MaxAbsVxx(IssmDouble* pmaxabsvx,bool process_units){/*{{{*/
     987
     988        int i;
     989        IssmDouble maxabsvx;
     990        IssmDouble node_maxabsvx;
     991        IssmDouble element_maxabsvx;
     992
     993        /*Go through elements, and request velocity: */
     994        maxabsvx=-INFINITY;
     995        for(i=0;i<this->elements->Size();i++){
     996                Element* element=(Element*)this->elements->GetObjectByOffset(i);
     997                element->MaxAbsVx(&element_maxabsvx,process_units);
     998                if(element_maxabsvx>maxabsvx) maxabsvx=element_maxabsvx;
     999        }
     1000
     1001        /*Figure out maximum across the cluster: */
     1002#ifdef _HAVE_MPI_
     1003        MPI_Reduce(&maxabsvx,&node_maxabsvx,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
     1004        MPI_Bcast(&node_maxabsvx,1,MPI_DOUBLE,0,IssmComm::GetComm());   
     1005        maxabsvx=node_maxabsvx;
     1006#endif
     1007
     1008        /*Assign output pointers:*/
     1009        *pmaxabsvx=maxabsvx;
     1010
     1011}/*}}}*/
     1012void FemModel::MaxAbsVyx(IssmDouble* pmaxabsvy,bool process_units){/*{{{*/
     1013
     1014        int i;
     1015        IssmDouble maxabsvy;
     1016        IssmDouble node_maxabsvy;
     1017        IssmDouble element_maxabsvy;
     1018
     1019        /*Go through elements, and request velocity: */
     1020        maxabsvy=-INFINITY;
     1021        for(i=0;i<this->elements->Size();i++){
     1022                Element* element=(Element*)this->elements->GetObjectByOffset(i);
     1023                element->MaxAbsVy(&element_maxabsvy,process_units);
     1024                if(element_maxabsvy>maxabsvy) maxabsvy=element_maxabsvy;
     1025        }
     1026
     1027        /*Figure out maximum across the cluster: */
     1028#ifdef _HAVE_MPI_
     1029        MPI_Reduce(&maxabsvy,&node_maxabsvy,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
     1030        MPI_Bcast(&node_maxabsvy,1,MPI_DOUBLE,0,IssmComm::GetComm());   
     1031        maxabsvy=node_maxabsvy;
     1032#endif
     1033
     1034        /*Assign output pointers:*/
     1035        *pmaxabsvy=maxabsvy;
     1036
     1037}/*}}}*/
     1038void FemModel::MaxAbsVzx(IssmDouble* pmaxabsvz,bool process_units){/*{{{*/
     1039
     1040        int i;
     1041        IssmDouble maxabsvz;
     1042        IssmDouble node_maxabsvz;
     1043        IssmDouble element_maxabsvz;
     1044
     1045        /*Go through elements, and request velocity: */
     1046        maxabsvz=-INFINITY;
     1047        for(i=0;i<this->elements->Size();i++){
     1048                Element* element=(Element*)this->elements->GetObjectByOffset(i);
     1049                element->MaxAbsVz(&element_maxabsvz,process_units);
     1050                if(element_maxabsvz>maxabsvz) maxabsvz=element_maxabsvz;
     1051        }
     1052
     1053        /*Figure out maximum across the cluster: */
     1054#ifdef _HAVE_MPI_
     1055        MPI_Reduce(&maxabsvz,&node_maxabsvz,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
     1056        MPI_Bcast(&node_maxabsvz,1,MPI_DOUBLE,0,IssmComm::GetComm());   
     1057        maxabsvz=node_maxabsvz;
     1058#endif
     1059
     1060        /*Assign output pointers:*/
     1061        *pmaxabsvz=maxabsvz;
     1062
     1063}/*}}}*/
     1064void FemModel::MaxVelx(IssmDouble* pmaxvel,bool process_units){/*{{{*/
     1065
     1066        int i;
     1067        IssmDouble maxvel;
     1068        IssmDouble node_maxvel;
     1069        IssmDouble element_maxvel;
     1070
     1071        /*Go through elements, and request velocity: */
     1072        maxvel=-INFINITY;
     1073        for(i=0;i<this->elements->Size();i++){
     1074                Element* element=(Element*)this->elements->GetObjectByOffset(i);
     1075                element->MaxVel(&element_maxvel,process_units);
     1076                if(element_maxvel>maxvel) maxvel=element_maxvel;
     1077        }
     1078
     1079        /*Figure out maximum across the cluster: */
     1080#ifdef _HAVE_MPI_
     1081        MPI_Reduce(&maxvel,&node_maxvel,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
     1082        MPI_Bcast(&node_maxvel,1,MPI_DOUBLE,0,IssmComm::GetComm());   
     1083        maxvel=node_maxvel;
     1084#endif
     1085
     1086        /*Assign output pointers:*/
     1087        *pmaxvel=maxvel;
     1088
     1089}/*}}}*/
     1090void FemModel::MaxVxx(IssmDouble* pmaxvx,bool process_units){/*{{{*/
     1091
     1092        int i;
     1093        IssmDouble maxvx;
     1094        IssmDouble node_maxvx;
     1095        IssmDouble element_maxvx;
     1096
     1097        /*Go through elements, and request velocity: */
     1098        maxvx=-INFINITY;
     1099        for(i=0;i<this->elements->Size();i++){
     1100                Element* element=(Element*)this->elements->GetObjectByOffset(i);
     1101                element->MaxVx(&element_maxvx,process_units);
     1102                if(element_maxvx>maxvx) maxvx=element_maxvx;
     1103        }
     1104
     1105        /*Figure out maximum across the cluster: */
     1106#ifdef _HAVE_MPI_
     1107        MPI_Reduce(&maxvx,&node_maxvx,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
     1108        MPI_Bcast(&node_maxvx,1,MPI_DOUBLE,0,IssmComm::GetComm());   
     1109        maxvx=node_maxvx;
     1110#endif
     1111
     1112        /*Assign output pointers:*/
     1113        *pmaxvx=maxvx;
     1114
     1115}/*}}}*/
     1116void FemModel::MaxVyx(IssmDouble* pmaxvy,bool process_units){/*{{{*/
     1117
     1118        int i;
     1119        IssmDouble maxvy;
     1120        IssmDouble node_maxvy;
     1121        IssmDouble element_maxvy;
     1122
     1123        /*Go through elements, and request velocity: */
     1124        maxvy=-INFINITY;
     1125        for(i=0;i<this->elements->Size();i++){
     1126                Element* element=(Element*)this->elements->GetObjectByOffset(i);
     1127                element->MaxVy(&element_maxvy,process_units);
     1128                if(element_maxvy>maxvy) maxvy=element_maxvy;
     1129        }
     1130
     1131        /*Figure out maximum across the cluster: */
     1132#ifdef _HAVE_MPI_
     1133        MPI_Reduce(&maxvy,&node_maxvy,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
     1134        MPI_Bcast(&node_maxvy,1,MPI_DOUBLE,0,IssmComm::GetComm());   
     1135        maxvy=node_maxvy;
     1136#endif
     1137
     1138        /*Assign output pointers:*/
     1139        *pmaxvy=maxvy;
     1140
     1141}/*}}}*/
     1142void FemModel::MaxVzx(IssmDouble* pmaxvz,bool process_units){/*{{{*/
     1143
     1144        int i;
     1145        IssmDouble maxvz;
     1146        IssmDouble node_maxvz;
     1147        IssmDouble element_maxvz;
     1148
     1149        /*Go through elements, and request velocity: */
     1150        maxvz=-INFINITY;
     1151        for(i=0;i<this->elements->Size();i++){
     1152                Element* element=(Element*)this->elements->GetObjectByOffset(i);
     1153                element->MaxVz(&element_maxvz,process_units);
     1154                if(element_maxvz>maxvz) maxvz=element_maxvz;
     1155        }
     1156
     1157        /*Figure out maximum across the cluster: */
     1158#ifdef _HAVE_MPI_
     1159        MPI_Reduce(&maxvz,&node_maxvz,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
     1160        MPI_Bcast(&node_maxvz,1,MPI_DOUBLE,0,IssmComm::GetComm());   
     1161        maxvz=node_maxvz;
     1162#endif
     1163
     1164        /*Assign output pointers:*/
     1165        *pmaxvz=maxvz;
     1166
     1167}/*}}}*/
     1168void FemModel::MinVelx(IssmDouble* pminvel,bool process_units){/*{{{*/
     1169
     1170        int i;
     1171        IssmDouble minvel;
     1172        IssmDouble node_minvel;
     1173        IssmDouble element_minvel;
     1174
     1175        /*Go through elements, and request velocity: */
     1176        minvel=INFINITY;
     1177        for(i=0;i<this->elements->Size();i++){
     1178                Element* element=(Element*)this->elements->GetObjectByOffset(i);
     1179                element->MinVel(&element_minvel,process_units);
     1180                if(element_minvel<minvel) minvel=element_minvel;
     1181        }
     1182
     1183        /*Figure out minimum across the cluster: */
     1184#ifdef _HAVE_MPI_
     1185        MPI_Reduce(&minvel,&node_minvel,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
     1186        MPI_Bcast(&node_minvel,1,MPI_DOUBLE,0,IssmComm::GetComm());   
     1187        minvel=node_minvel;
     1188#endif
     1189
     1190        /*Assign output pointers:*/
     1191        *pminvel=minvel;
     1192
     1193}/*}}}*/
     1194void FemModel::MinVxx(IssmDouble* pminvx,bool process_units){/*{{{*/
     1195
     1196        int i;
     1197        IssmDouble minvx;
     1198        IssmDouble node_minvx;
     1199        IssmDouble element_minvx;
     1200
     1201        /*Go through elements, and request velocity: */
     1202        minvx=INFINITY;
     1203        for(i=0;i<this->elements->Size();i++){
     1204                Element* element=(Element*)this->elements->GetObjectByOffset(i);
     1205                element->MinVx(&element_minvx,process_units);
     1206                if(element_minvx<minvx) minvx=element_minvx;
     1207        }
     1208
     1209        /*Figure out minimum across the cluster: */
     1210#ifdef _HAVE_MPI_
     1211        MPI_Reduce(&minvx,&node_minvx,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
     1212        MPI_Bcast(&node_minvx,1,MPI_DOUBLE,0,IssmComm::GetComm());   
     1213        minvx=node_minvx;
     1214#endif
     1215
     1216        /*Assign output pointers:*/
     1217        *pminvx=minvx;
     1218
     1219}/*}}}*/
     1220void FemModel::MinVyx(IssmDouble* pminvy,bool process_units){/*{{{*/
     1221
     1222        int i;
     1223        IssmDouble minvy;
     1224        IssmDouble node_minvy;
     1225        IssmDouble element_minvy;
     1226
     1227        /*Go through elements, and request velocity: */
     1228        minvy=INFINITY;
     1229        for(i=0;i<this->elements->Size();i++){
     1230                Element* element=(Element*)this->elements->GetObjectByOffset(i);
     1231                element->MinVy(&element_minvy,process_units);
     1232                if(element_minvy<minvy) minvy=element_minvy;
     1233        }
     1234
     1235        /*Figure out minimum across the cluster: */
     1236#ifdef _HAVE_MPI_
     1237        MPI_Reduce(&minvy,&node_minvy,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
     1238        MPI_Bcast(&node_minvy,1,MPI_DOUBLE,0,IssmComm::GetComm());   
     1239        minvy=node_minvy;
     1240#endif
     1241
     1242        /*Assign output pointers:*/
     1243        *pminvy=minvy;
     1244
     1245}/*}}}*/
     1246void FemModel::MinVzx(IssmDouble* pminvz,bool process_units){/*{{{*/
     1247
     1248        int i;
     1249        IssmDouble minvz;
     1250        IssmDouble node_minvz;
     1251        IssmDouble element_minvz;
     1252
     1253        /*Go through elements, and request velocity: */
     1254        minvz=INFINITY;
     1255        for(i=0;i<this->elements->Size();i++){
     1256                Element* element=(Element*)this->elements->GetObjectByOffset(i);
     1257                element->MinVz(&element_minvz,process_units);
     1258                if(element_minvz<minvz) minvz=element_minvz;
     1259        }
     1260
     1261        /*Figure out minimum across the cluster: */
     1262#ifdef _HAVE_MPI_
     1263        MPI_Reduce(&minvz,&node_minvz,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
     1264        MPI_Bcast(&node_minvz,1,MPI_DOUBLE,0,IssmComm::GetComm());   
     1265        minvz=node_minvz;
     1266#endif
     1267
     1268        /*Assign output pointers:*/
     1269        *pminvz=minvz;
     1270
     1271}/*}}}*/
     1272void FemModel::TotalSmbx(IssmDouble* pSmb,bool process_units){/*{{{*/
     1273
     1274        IssmDouble local_smb = 0;
     1275        IssmDouble total_smb;
     1276
     1277        for(int i=0;i<this->elements->Size();i++){
     1278                Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
     1279                local_smb+=element->TotalSmb();
     1280        }
     1281#ifdef _HAVE_MPI_
     1282        MPI_Reduce(&local_smb,&total_smb,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
     1283        MPI_Bcast(&total_smb,1,MPI_DOUBLE,0,IssmComm::GetComm());
     1284#else
     1285        total_smb=local_smb;
     1286#endif
     1287
     1288        /*Assign output pointers: */
     1289        *pSmb=total_smb;
     1290
     1291}/*}}}*/
     1292void FemModel::IceVolumex(IssmDouble* pV,bool process_units){/*{{{*/
     1293
     1294        IssmDouble local_ice_volume = 0;
     1295        IssmDouble total_ice_volume;
     1296
     1297        for(int i=0;i<this->elements->Size();i++){
     1298                Element* element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
     1299                local_ice_volume+=element->IceVolume();
     1300        }
     1301        #ifdef _HAVE_MPI_
     1302        MPI_Reduce(&local_ice_volume,&total_ice_volume,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
     1303        MPI_Bcast(&total_ice_volume,1,MPI_DOUBLE,0,IssmComm::GetComm());
     1304        #else
     1305        total_ice_volume=local_ice_volume;
     1306        #endif
     1307
     1308        /*Assign output pointers: */
     1309        *pV=total_ice_volume;
     1310
     1311}/*}}}*/
     1312void FemModel::ElementResponsex(IssmDouble* presponse,int response_enum,bool process_units){/*{{{*/
     1313
     1314        int found=0;
     1315        int sumfound=0;
     1316        int cpu_found=-1;
     1317        int index;
     1318        IssmDouble response;
     1319        Element* element=NULL;
     1320
     1321        /*retrieve element we are interested in: */
     1322        this->parameters->FindParam(&index,IndexEnum);
     1323        int my_rank=IssmComm::GetRank();
     1324
     1325        /*now, go through our elements, and retrieve the one with this id: index: */
     1326        for(int i=0;i<this->elements->Size();i++){
     1327                element=dynamic_cast<Element*>(this->elements->GetObjectByOffset(i));
     1328                if (element->Id()==index){
     1329                        found=1;
     1330                        cpu_found=my_rank;
     1331                        break;
     1332                }
     1333        }
     1334
     1335        /*Broadcast whether we found the element: */
     1336#ifdef _HAVE_MPI_
     1337        MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
     1338        if(!sumfound)_error_("could not find material with id" << index << " to compute ElementResponse");
     1339#endif
     1340
     1341        /*Ok, we found the element, compute responseocity: */
     1342        if(my_rank==cpu_found){
     1343                element->ElementResponse(&response,response_enum,IuToExtEnum);
     1344        }
     1345
     1346        /*Broadcast and plug into response: */
     1347#ifdef _HAVE_MPI_
     1348        MPI_Allreduce ( &cpu_found,&cpu_found,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
     1349        MPI_Bcast(&response,1,MPI_DOUBLE,cpu_found,IssmComm::GetComm());
     1350#endif
     1351
     1352        /*Assign output pointers: */
     1353        *presponse=response;
     1354
     1355}/*}}}*/
     1356#endif
     1357#ifdef _HAVE_CONTROL_
     1358void FemModel::ThicknessAbsGradientx( IssmDouble* pJ, bool process_units, int weight_index){/*{{{*/
     1359
     1360
     1361        /*Intermediary*/
     1362        int i;
     1363        Element* element=NULL;
     1364
     1365        /*output: */
     1366        IssmDouble J=0;
     1367        IssmDouble J_sum;
     1368
     1369        /*Compute Misfit: */
     1370        for (i=0;i<elements->Size();i++){
     1371                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
     1372                J+=element->ThicknessAbsGradient(process_units,weight_index);
     1373        }
     1374
     1375        /*Sum all J from all cpus of the cluster:*/
     1376        #ifdef _HAVE_MPI_
     1377        MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
     1378        MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
     1379        J=J_sum;
     1380        #endif
     1381
     1382        /*Assign output pointers: */
     1383        *pJ=J;
     1384}
     1385/*}}}*/
     1386void FemModel::CostFunctionx(IssmDouble* pJ){/*{{{*/
     1387
     1388
     1389        /*Intermediary*/
     1390        int      num_responses;
     1391        Element *element       = NULL;
     1392        int     *responses     = NULL;
     1393
     1394        /*output: */
     1395        IssmDouble J,Jplus;
     1396
     1397        /*Recover parameters*/
     1398        parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
     1399        parameters->FindParam(&responses,NULL,NULL,StepResponsesEnum);
     1400
     1401        /*Get response*/
     1402        J=0;
     1403        for(int i=0;i<num_responses;i++){
     1404                this->Responsex(&Jplus,EnumToStringx(responses[i]),false,i); //False means DO NOT process units
     1405                J+=Jplus;
     1406        }
     1407
     1408        /*Assign output pointers: */
     1409        xDelete<int>(responses);
     1410        *pJ=J;
     1411}
     1412/*}}}*/
     1413#endif
     1414#ifdef  _HAVE_DAKOTA_
     1415void FemModel::DakotaResponsesx(double* d_responses,char** responses_descriptors,int numresponsedescriptors,int d_numresponses){/*{{{*/
     1416
     1417
     1418        int        i,j;
     1419        int        my_rank;
     1420        bool       process_units = true;
     1421
     1422        /*intermediary: */
     1423        char   root[50];
     1424        int    index;
     1425        int    npart;
     1426        double femmodel_response;
     1427        int    flag;
     1428        double *vertex_response   = NULL;
     1429        double *qmu_response      = NULL;
     1430        double *responses_pointer = NULL;
     1431
     1432        /*retrieve npart: */
     1433        parameters->FindParam(&npart,QmuNumberofpartitionsEnum);
     1434        my_rank=IssmComm::GetRank();
     1435
     1436        /*save the d_responses pointer: */
     1437        responses_pointer=d_responses;
     1438
     1439        //watch out, we have more d_numresponses than numresponsedescriptors, because the responses have been expanded if they were scaled.
     1440        //because we don't know the d_responses descriptors (the scaled ones) we can't key off them, so we will key off the responses_descriptors: */
     1441
     1442        for(i=0;i<numresponsedescriptors;i++){
     1443
     1444                flag=DescriptorIndex(root,&index,responses_descriptors[i]);
     1445
     1446                if(flag==ScaledEnum){
     1447
     1448                        /*this response was scaled. pick up the response from the inputs: */
     1449                        GetVectorFromInputsx(&vertex_response,elements,nodes, vertices, loads, materials, parameters, StringToEnumx(root),VertexEnum);
     1450
     1451                        /*Now, average it onto the partition nodes: */
     1452                        AverageOntoPartitionx(&qmu_response,elements,nodes,vertices,loads,materials,parameters,vertex_response);
     1453
     1454                        /*Copy onto our dakota responses: */
     1455                        if(my_rank==0){
     1456                                /*plug response: */
     1457                                for(j=0;j<npart;j++)responses_pointer[j]=qmu_response[j];
     1458
     1459                                /*increment response_pointer :*/
     1460                                responses_pointer+=npart;
     1461                        }
     1462
     1463                        /*Free ressources:*/
     1464                        xDelete<double>(vertex_response);
     1465                        xDelete<double>(qmu_response);
     1466
     1467                }
     1468                else if (flag==IndexedEnum){
     1469
     1470                        /*indexed response: plug index into parameters and call response module: */
     1471                        parameters->SetParam(index,IndexEnum);
     1472
     1473                        this->Responsex(&femmodel_response,root,process_units,0);//0 is the index for weights
     1474
     1475                        if(my_rank==0){
     1476                                /*plug response: */
     1477                                responses_pointer[0]=femmodel_response;
     1478
     1479                                /*increment response_pointer :*/
     1480                                responses_pointer++;
     1481                        }
     1482                }
     1483                else if (flag==NodalEnum){
     1484                        _error_("nodal response functions not supported yet!");
     1485
     1486                        /*increment response_pointer :*/
     1487                        responses_pointer++;
     1488                }
     1489                else if (flag==RegularEnum){
     1490
     1491                        /*perfectly normal response function: */
     1492                        this->Responsex(&femmodel_response,root,process_units,0);//0 is the weight index
     1493
     1494                        if(my_rank==0){
     1495                                /*plug response: */
     1496                                responses_pointer[0]=femmodel_response;
     1497
     1498                                /*increment response_pointer :*/
     1499                                responses_pointer++;
     1500                        }
     1501                }
     1502                else _error_("flag type " << flag << " not supported yet for response analysis");
     1503        }
     1504
     1505        /*Synthesize echo: {{{*/
     1506        if(my_rank==0){
     1507                _printString_("   responses: " << d_numresponses << ": ");
     1508                for(i=0;i<d_numresponses-1;i++)_printString_(d_responses[i] << "|");
     1509                _printString_(d_responses[d_numresponses-1]);
     1510                _printLine_("");
     1511        }
     1512        /*}}}*/
     1513
     1514}
     1515/*}}}*/
     1516#endif
  • issm/trunk/src/c/classes/FemModel.h

    r13395 r13975  
    1919class Loads;
    2020class Materials;
     21class Profiler;
     22class Elements;
    2123/*}}}*/
    22 
    2324
    2425class FemModel {
     
    2829        public:
    2930
    30                 int                 nummodels;
    31                 int                 solution_type;
    32                 int*                analysis_type_list; //list of analyses this femmodel is going to carry out
    33                 int                 analysis_counter; //counter into analysis_type_list
    34                
    35                 Elements*           elements; //elements (one set for all analyses)
    36                 Nodes*              nodes; //one set of nodes
    37                 Vertices*           vertices; //one set of vertices
    38                 Constraints*        constraints; //one set of constraints. each constraint knows which analysis_type it handles
    39                 Loads*              loads;  //one set of constraints. each constraint knows which analysis_type it handles
    40                 Materials*          materials;  //one set of materials, for each element
    41                 Parameters*         parameters; //one set of parameters, independent of the analysis_type
    42                 Results*            results; //results that cannot be fit into the elements (such as one time constants, arrays, strings, etc ...)
     31                int          nummodels;
     32                int          solution_type;
     33                int         *analysis_type_list;   //list of analyses this femmodel is going to carry out
     34                int          analysis_counter;     //counter into analysis_type_list
     35
     36                Profiler*    profiler;             //keep time, cpu and mem statistics while we are running.
     37
     38                Elements    *elements;             //elements (one set for all analyses)
     39                Nodes       *nodes;                //one set of nodes
     40                Vertices    *vertices;             //one set of vertices
     41                Constraints *constraints;          //one set of constraints. each constraint knows which analysis_type it handles
     42                Loads       *loads;                //one set of constraints. each constraint knows which analysis_type it handles
     43                Materials   *materials;            //one set of materials, for each element
     44                Parameters  *parameters;           //one set of parameters, independent of the analysis_type
     45                Results     *results;              //results that cannot be fit into the elements
     46                COMM        comm;                  //communicator for this particular model
    4347
    4448                /*constructors, destructors: */
    45                 FemModel(char* rootpath, char* inputfilename, char* outputfilename, const int solution_type,const int* analyses,const int nummodels);
     49                FemModel(int argc,char** argv,COMM comm_init);
     50                FemModel(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int solution_type,const int* analyses,const int nummodels);
    4651                ~FemModel();
    4752
    48                 /*Methods: */
     53                /*Methods:*/
     54                void AllocateSystemMatrices(Matrix<IssmDouble>** pKff,Matrix<IssmDouble>** pKfs,Vector<IssmDouble>** pdf,Vector<IssmDouble>** ppf);
     55                void CreateJacobianMatrixx(Matrix<IssmDouble>** pJff,IssmDouble kmax);
    4956                void Echo();
     57                void InitFromFiles(char* rootpath, char* inputfilename, char* outputfilename, char* petscfilename, char* lockfilename, const int solution_type,const int* analyses,const int nummodels);
     58                void MatrixNonzeros(int** pd_nnz,int** po_nnz,int set1enum,int set2enum);
     59                void Solve(void);
     60                void OutputResults(void);
     61                void SetStaticComm();
     62                void SetCurrentConfiguration(int configuration_type);
     63                void SetCurrentConfiguration(int configuration_type,int analysis_type);
    5064
    51                 /*Fem: */
    52                 void  SetCurrentConfiguration(int configuration_type);
    53                 void  SetCurrentConfiguration(int configuration_type,int analysis_type);
    54 
     65                /*Modules*/
     66                #ifdef _HAVE_RESPONSES_
     67                void MassFluxx(IssmDouble* presponse,bool process_units);
     68                void MaxAbsVxx(IssmDouble* presponse,bool process_units);
     69                void MaxAbsVyx(IssmDouble* presponse,bool process_units);
     70                void MaxAbsVzx(IssmDouble* presponse,bool process_units);
     71                void MaxVelx(IssmDouble* presponse,bool process_units);
     72                void MaxVxx(IssmDouble* presponse,bool process_units);
     73                void MaxVyx(IssmDouble* presponse,bool process_units);
     74                void MaxVzx(IssmDouble* presponse,bool process_units);
     75                void MinVelx(IssmDouble* presponse,bool process_units);
     76                void MinVxx(IssmDouble* presponse,bool process_units);
     77                void MinVyx(IssmDouble* presponse,bool process_units);
     78                void MinVzx(IssmDouble* presponse,bool process_units);
     79                void TotalSmbx(IssmDouble* pSmb,bool process_units);
     80                void IceVolumex(IssmDouble* pV,bool process_units);
     81                void ElementResponsex(IssmDouble* presponse,int response_enum,bool process_units);
     82                #endif
     83                #ifdef  _HAVE_DAKOTA_
     84                void DakotaResponsesx(double* d_responses,char** responses_descriptors,int numresponsedescriptors,int d_numresponses);
     85                #endif
     86                void RequestedOutputsx(int* requested_outputs, int numoutputs);
     87                void RequestedDependentsx(void);
     88                void Responsex(IssmDouble* presponse,int response_descriptor_enum,bool process_units,int weight_index);
     89                void Responsex(IssmDouble* presponse,const char* response_descriptor,bool process_units,int weight_index);
     90                #ifdef _HAVE_CONTROL_
     91                void CostFunctionx( IssmDouble* pJ);
     92                void ThicknessAbsGradientx( IssmDouble* pJ, bool process_units,int weight_index);
     93                #endif
     94                void SystemMatricesx(Matrix<IssmDouble>** pKff, Matrix<IssmDouble>** pKfs, Vector<IssmDouble>** ppf, Vector<IssmDouble>** pdf, IssmDouble* pkmax);
     95                void TimeAdaptx(IssmDouble* pdt);
     96                void UpdateConstraintsx(void);
     97                int  UpdateVertexPositionsx(void);
    5598};
    5699
  • issm/trunk/src/c/classes/Hook.cpp

    r13395 r13975  
    22 * \brief: implementation of the Hook object: see Hook.h for more explanations.
    33 */
    4 
    54
    65#ifdef HAVE_CONFIG_H
     
    1817#include "../include/include.h"
    1918
    20 
    2119/*Constructor/Destructors*/
    2220/*FUNCTION Hook::Hook(){{{*/
    2321Hook::Hook(){
    24         this->num=0;
    25         this->objects=NULL;
    26         this->ids=NULL;
    27         this->offsets=NULL;
    28         return;
     22        this->num     = 0;
     23        this->objects = NULL;
     24        this->ids     = NULL;
     25        this->offsets = NULL;
    2926}
    3027/*}}}*/
    3128/*FUNCTION Hook::Hook(int* ids, int num){{{*/
    3229Hook::Hook(int* in_ids, int in_num){
    33 
    34         /*Intermediaries*/
    35         int i;
    3630
    3731        /*Get number of objects to hook*/
     
    4135        if (num==0){
    4236                /*Empty hook*/
    43                 this->ids=NULL;
    44                 this->objects=NULL;
    45                 this->offsets=NULL;
     37                this->ids     = NULL;
     38                this->objects = NULL;
     39                this->offsets = NULL;
    4640        }
    4741        else{
     
    5246
    5347                /*Copy ids: */
    54                 for (i=0;i<this->num;i++){
    55                         this->ids[i]=in_ids[i];
    56                         this->objects[i]=NULL;
    57                         this->offsets[i]=0;
     48                for(int i=0;i<this->num;i++){
     49                        this->ids[i]     = in_ids[i];
     50                        this->objects[i] = NULL;
     51                        this->offsets[i] = 0;
    5852                }
    5953        }
     
    6256/*FUNCTION Hook::~Hook(){{{*/
    6357Hook::~Hook(){
    64         /*deallocate: */
    6558        xDelete<Object*>(this->objects);
    6659        xDelete<int>(this->ids);
    6760        xDelete<int>(this->offsets);
    68         return;
    6961}
    7062/*}}}*/
     
    121113Object* Hook::copy(void){
    122114
    123         int i;
    124 
    125115        /*output: */
    126116        Hook* output=NULL;
     
    132122        output->num=this->num;
    133123        if(output->num){
    134                 output->objects=xNew<Object*>(output->num);
    135                 output->ids=xNew<int>(output->num);
    136                 output->offsets=xNew<int>(output->num);
    137         }
    138        
    139         for(i=0;i<output->num;i++){
    140                 output->objects[i]=this->objects[i];
    141                 output->offsets[i]=this->offsets[i];
    142                 output->ids[i]=this->ids[i];
     124                output->objects = xNew<Object*>(output->num);
     125                output->ids     = xNew<int>(output->num);
     126                output->offsets = xNew<int>(output->num);
     127        }
     128
     129        for(int i=0;i<output->num;i++){
     130                output->objects[i] = this->objects[i];
     131                output->offsets[i] = this->offsets[i];
     132                output->ids[i]     = this->ids[i];
    143133        }
    144134
     
    183173                /*Now, for this->objects that did not get resolved, and for which we have no offset, chase them in the dataset, by id: */
    184174                if(this->objects[i]==NULL){
    185                         this->objects[i]=(Object*)dataset->GetObjectById(this->offsets+i,this->ids[i]); //remember the offset for later on.
     175                        this->objects[i]=dynamic_cast<Object*>(dataset->GetObjectById(this->offsets+i,this->ids[i])); //remember the offset for later on.
    186176                        /*check the id is correct!: */
    187177                        if (this->objects[i]->Id()!=this->ids[i]) _error_("wrong id: " << this->objects[i]->Id() << " vs " << this->ids[i] << "  in resolved pointer!");
     
    192182/*FUNCTION Hook::delivers{{{*/
    193183Object* Hook::delivers(void){
    194        
     184
    195185        /*first, check that we only have one T object in our object list: */
    196186        if (this->num!=1) _error_("trying to delivery a single hook object when hook holds " << this->num << " objects" << "\n");
     
    230220/*FUNCTION Hook::Spawn{{{*/
    231221Hook* Hook::Spawn(int* indices, int numindices){
    232 
    233         int i;
    234222
    235223        /*output: */
     
    246234
    247235        /*Else, check that we are requesting a half of num*/
    248         if (numindices>this->num) _error_("Cannot spawn hook with " << numindices << " objects from a Hook of " << this->num << " objects");
     236        if(numindices>this->num) _error_("Cannot spawn hook with " << numindices << " objects from a Hook of " << this->num << " objects");
    249237
    250238        /*go pickup the correct objects, ids and offsets :*/
     
    252240        if(output->num<1) _error_("Trying to spawn an empty ElementProperties!");
    253241
    254         output->objects=xNew<Object*>(output->num);
    255         output->ids=xNew<int>(output->num);
    256         output->offsets=xNew<int>(output->num);
    257 
    258         for(i=0;i<output->num;i++){
    259                 output->objects[i]=this->objects[indices[i]];
    260                 output->ids[i]=this->ids[indices[i]];
    261                 output->offsets[i]=this->offsets[indices[i]];
     242        output->objects = xNew<Object*>(output->num);
     243        output->ids     = xNew<int>(output->num);
     244        output->offsets = xNew<int>(output->num);
     245
     246        for(int i=0;i<output->num;i++){
     247                output->objects[i] = this->objects[indices[i]];
     248                output->ids[i]     = this->ids[indices[i]];
     249                output->offsets[i] = this->offsets[indices[i]];
    262250        }
    263251
  • issm/trunk/src/c/classes/Hook.h

    r13395 r13975  
    1919        private:
    2020
    21                 int        num; //number of objects being hooked onto
    22                 Object**           objects; //list of object pointers. we do not allocate objects, just a list a pointers, that will get to point to the real objects from a dataset.
    23                 int*   ids;     //list of object ids, to go look for them in datasets.
    24                 int*   offsets;  //list of object offsets into datasets, to speed up lookup.
     21                int      num;      //number of objects being hooked onto
     22                Object **objects;   //list of object pointers
     23                int     *ids;       //list of object ids, to go look for them in datasets.
     24                int     *offsets;   //list of object offsets into datasets, to speed up lookup.
    2525
    2626        public:
  • issm/trunk/src/c/classes/IoModel.cpp

    r13395 r13975  
    1717#include "./classes.h"
    1818#include "../io/io.h"
    19 #include "./Container/Parameters.h"
     19#include "../Container/Parameters.h"
    2020#include "../shared/shared.h"
    21 #include "../io/io.h"
    2221#include "../include/include.h"
    2322
     
    2827        this->independents=NULL;
    2928        this->constants=NULL;
    30        
     29
    3130        this->my_elements=NULL;
    3231        this->my_nodes=NULL;
     
    3433        this->singlenodetoelementconnectivity=NULL;
    3534        this->numbernodetoelementconnectivity=NULL;
    36        
     35
    3736        this->nodecounter=0;
    3837        this->loadcounter=0;
     
    4241/*FUNCTION IoModel::IoModel(FILE*  iomodel_handle){{{*/
    4342IoModel::IoModel(FILE* iomodel_handle){
    44        
     43
    4544        /*First, keep track of the file handle: */
    4645        this->fid=iomodel_handle;
     
    4847        /*Check that Enums are Synchronized*/
    4948        this->CheckEnumSync();
     49
     50        /*Initialize data: */
     51        this->data=xNew<IssmDouble*>(MaximumNumberOfEnums);
     52        for(int i=0;i<MaximumNumberOfEnums;i++) this->data[i]=NULL;
     53
     54        /*If we are running in AD mode, we need to start the trace and declare our independent variables now,
     55         *and prevent them from being erased during successive calls to iomodel->FetchConstants, iomodel->FetchData and
     56         iomodel->DeleteData:*/
     57        this->DeclareIndependents();
    5058
    5159        /*Initialize and read constants:*/
     
    5361        this->FetchConstants(); /*this routine goes through the input file, and fetches bools, ints, IssmDoubles and strings only, nothing memory intensive*/
    5462
    55         /*Initialize data: */
    56         this->data=xNew<IssmDouble*>(MaximumNumberOfEnums);
    57         for(int i=0;i<MaximumNumberOfEnums;i++) this->data[i]=NULL;
    58 
    59         /*Initialize array detecting whether data[i] is an independent AD mode variable: */
    60         this->independents=xNew<bool>(MaximumNumberOfEnums);
    61         for(int i=0;i<MaximumNumberOfEnums;i++) this->independents[i]=false;
    62        
    6363        /*Initialize permanent data: */
    6464        this->my_elements=NULL;
     
    6767        this->singlenodetoelementconnectivity=NULL;
    6868        this->numbernodetoelementconnectivity=NULL;
    69        
     69
    7070        this->nodecounter=0;
    7171        this->loadcounter=0;
     
    9191        xDelete<IssmDouble*>(this->data);
    9292        xDelete<bool>(this->independents);
     93        if(this->independent_objects)delete this->independent_objects;
    9394        xDelete<bool>(this->my_elements);
    9495        xDelete<bool>(this->my_nodes);
     
    102103void  IoModel::CheckEnumSync(void){
    103104
    104         extern int my_rank;
     105        int my_rank;
    105106        int record_enum = 0;
     107
     108        /*recover my_rank:*/
     109        my_rank=IssmComm::GetRank();
    106110
    107111        /*Check that some fields have been allocated*/
     
    182186
    183187        /*Find constant*/
    184         Param* param=(Param*)this->constants->FindParamObject(constant_enum);
     188        Param* param=dynamic_cast<Param*>(this->constants->FindParamObject(constant_enum));
    185189        if(!param) _error_("Constant " << EnumToStringx(constant_enum) << " not found in iomodel");
    186190
    187         return (Param*)param->copy();
     191        return dynamic_cast<Param*>(param->copy());
    188192}
    189193/*}}}*/
     
    195199
    196200        return this->data[data_enum];
     201}
     202/*}}}*/
     203/*FUNCTION IoModel::DeclareIndependents{{{*/
     204void IoModel::DeclareIndependents(void){
     205
     206        int         i;
     207        bool        autodiff                = false;
     208        int         num_independent_objects;
     209
     210        int *names = NULL;
     211        int *types = NULL;
     212
     213        int         numberofvertices;
     214        int         dummy;
     215        bool        keep=false;
     216
     217        /*Initialize array detecting whether data[i] is an independent AD mode variable: */
     218        this->independents=xNew<bool>(MaximumNumberOfEnums);
     219        for(i=0;i<MaximumNumberOfEnums;i++) this->independents[i]=false;
     220
     221        this->FetchData(&autodiff,AutodiffIsautodiffEnum);
     222        if(autodiff){
     223
     224                this->FetchData(&numberofvertices,MeshNumberofverticesEnum);
     225
     226                #ifdef _HAVE_ADOLC_
     227
     228                /*Start trace: {{{*/
     229                this->FetchData(&keep,AutodiffKeepEnum);
     230                if(keep)trace_on(1,1);
     231                else    trace_on(1);
     232
     233                /*}}}*/
     234                /*build dataset made of independent objects: {{{*/
     235                this->independent_objects=new DataSet();
     236                this->FetchData(&num_independent_objects,AutodiffNumIndependentObjectsEnum);
     237                if(num_independent_objects){
     238                        this->FetchData(&names,&dummy,&dummy,AutodiffIndependentObjectNamesEnum);
     239                        this->FetchData(&types,&dummy,&dummy,AutodiffIndependentObjectTypesEnum);
     240
     241                        /*create independent objects, and at the same time, fetch the corresponding independent variables,
     242                         *and declare them as such in ADOLC: */
     243                        for(i=0;i<num_independent_objects;i++){
     244
     245                                IndependentObject* independent_object=NULL;
     246                                independent_object=new IndependentObject(names[i],types[i],numberofvertices);
     247
     248                                /*add to independent_objects dataset:*/
     249                                this->independent_objects->AddObject(independent_object);
     250
     251                                /*now go fetch the independent variable: */
     252                                independent_object->FetchIndependent(this); //supply the pointer to iomodel.
     253                        }
     254                        xDelete<int>(names);
     255                        xDelete<int>(types);
     256                } /*}}}*/
     257
     258                #else
     259                /*if we asked for AD computations, we have a problem!: */
     260                _error_("Cannot carry out AD mode computations without support of ADOLC compiled in!");
     261                #endif
     262        }
     263        else this->independent_objects=NULL;
     264
    197265}
    198266/*}}}*/
     
    211279                dataenum=va_arg(ap, int);
    212280                _assert_(dataenum<MaximumNumberOfEnums);
    213                
     281
    214282                /*do not erase independent variables for the AD mode computations!: */
    215283                if (!this->independents[dataenum]) xDelete<IssmDouble>(this->data[dataenum]);
     
    227295void  IoModel::FetchConstants(void){
    228296
    229         extern int my_rank;
    230         extern int num_procs;
    231        
     297        int my_rank;
     298
    232299        /*record descriptions; */
    233300        int record_enum;
     
    238305        int  booleanint=0;
    239306        int  integer=0;
    240         IssmPDouble scalar=0;
     307        IssmPDouble pscalar=0;
     308        IssmDouble scalar=0;
    241309        char* string=NULL;
    242310        int   string_size;
     311
     312        /*recover my_rank:*/
     313        my_rank=IssmComm::GetRank();
    243314
    244315        /*Check that some fields have been allocated*/
     
    248319        /*Go find in the binary file, the position of the data we want to fetch: */
    249320        if(my_rank==0){ //cpu 0{{{
    250        
     321
    251322                /*First set FILE* position to the beginning of the file: */
    252323                fseek(this->fid,0,SEEK_SET);
     
    259330                                record_code=0; //0 means bailout
    260331                                #ifdef _HAVE_MPI_
    261                                 MPI_Bcast(&record_code,1,MPI_INT,0,MPI_COMM_WORLD);  /*tell others cpus we are bailing: */
     332                                MPI_Bcast(&record_code,1,MPI_INT,0,IssmComm::GetComm());  /*tell others cpus we are bailing: */
    262333                                #endif
    263334                                break;
    264335                        }
    265336                        else{
    266                        
     337
    267338                                /* Read the record length and the data type code: */
    268339                                fread(&record_length,sizeof(int),1,this->fid);
    269340                                fread(&record_code,sizeof(int),1,this->fid);
    270                                        
     341
    271342                                #ifdef _HAVE_MPI_
    272343                                /*Tell other cpus what we are doing: */
    273                                 MPI_Bcast(&record_code,1,MPI_INT,0,MPI_COMM_WORLD);  /*tell other cpus what we are going to do: */
     344                                MPI_Bcast(&record_code,1,MPI_INT,0,IssmComm::GetComm());  /*tell other cpus what we are going to do: */
    274345
    275346                                /*Tell other cpus the name of the data, then branch according to the data type: */
    276                                 MPI_Bcast(&record_enum,1,MPI_INT,0,MPI_COMM_WORLD); 
    277                                 MPI_Bcast(&record_length,1,MPI_INT,0,MPI_COMM_WORLD); 
     347                                MPI_Bcast(&record_enum,1,MPI_INT,0,IssmComm::GetComm()); 
     348                                MPI_Bcast(&record_length,1,MPI_INT,0,IssmComm::GetComm()); 
    278349                                #endif
    279                                
     350
    280351                                switch(record_code){
    281352                                        case 1:
     
    283354                                                if(fread(&booleanint,sizeof(int),1,this->fid)!=1) _error_("could not read boolean ");
    284355                                                #ifdef _HAVE_MPI_
    285                                                 MPI_Bcast(&booleanint,1,MPI_INT,0,MPI_COMM_WORLD);
     356                                                MPI_Bcast(&booleanint,1,MPI_INT,0,IssmComm::GetComm());
    286357                                                #endif
    287358
     
    294365                                                if(fread(&integer,sizeof(int),1,this->fid)!=1) _error_("could not read integer ");
    295366                                                #ifdef _HAVE_MPI_
    296                                                 MPI_Bcast(&integer,1,MPI_INT,0,MPI_COMM_WORLD);
     367                                                MPI_Bcast(&integer,1,MPI_INT,0,IssmComm::GetComm());
    297368                                                #endif
    298369
     
    302373                                                break;
    303374                                        case 3:
    304                                                 /*Read the scalar and broadcast it to other cpus:*/
    305                                                 if(fread(&scalar,sizeof(IssmPDouble),1,this->fid)!=1) _error_("could not read scalar ");
    306                                                 #ifdef _HAVE_MPI_
    307                                                 MPI_Bcast(&scalar,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
    308                                                 #endif
     375                                                /*Read the scalar and broadcast it to other cpus. However, if this record has already
     376                                                 * been read in DeclareIndependents, we should not re-read it, but grab it from the iomodel->data
     377                                                 * slots: */
     378                                                if(this->independents[record_enum]){
     379                                                        scalar=*(this->data[record_enum]);
     380                                                }
     381                                                else{
     382                                                        if(fread(&pscalar,sizeof(IssmPDouble),1,this->fid)!=1) _error_("could not read scalar ");
     383                                                        #ifdef _HAVE_MPI_
     384                                                        MPI_Bcast(&pscalar,1,MPI_DOUBLE,0,IssmComm::GetComm());
     385                                                        #endif
     386                                                        scalar=reCast<IssmDouble>(pscalar);
     387                                                }
    309388
    310389                                                /*create DoubleParam: */
     
    316395                                                if(fread(&string_size,sizeof(int),1,this->fid)!=1) _error_("could not read length of string ");
    317396                                                #ifdef _HAVE_MPI_
    318                                                 MPI_Bcast(&string_size,1,MPI_INT,0,MPI_COMM_WORLD);
     397                                                MPI_Bcast(&string_size,1,MPI_INT,0,IssmComm::GetComm());
    319398                                                #endif
    320399
     
    326405                                                        if(fread(string,string_size*sizeof(char),1,this->fid)!=1)_error_(" could not read string ");
    327406                                                        #ifdef _HAVE_MPI_
    328                                                         MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD);
     407                                                        MPI_Bcast(string,string_size,MPI_CHAR,0,IssmComm::GetComm());
    329408                                                        #endif
    330409                                                }
     
    333412                                                        string[0]='\0';
    334413                                                }
    335                                                
     414
    336415                                                /*Add string to parameters: */
    337416                                                this->constants->AddObject(new StringParam(record_enum,string));
     
    384463        else{ //cpu ~0 {{{
    385464                for(;;){ //wait on cpu 0
    386                         MPI_Bcast(&record_code,1,MPI_INT,0,MPI_COMM_WORLD);  /*get from cpu 0 what we are going to do: */
     465                        MPI_Bcast(&record_code,1,MPI_INT,0,IssmComm::GetComm());  /*get from cpu 0 what we are going to do: */
    387466                        if(record_code==0){
    388467                                break; //we are done, break from the loop
    389468                        }
    390469                        else{
    391                                 MPI_Bcast(&record_enum,1,MPI_INT,0,MPI_COMM_WORLD);   //get from cpu 0 name of the data
    392                                 MPI_Bcast(&record_length,1,MPI_INT,0,MPI_COMM_WORLD); 
     470                                MPI_Bcast(&record_enum,1,MPI_INT,0,IssmComm::GetComm());   //get from cpu 0 name of the data
     471                                MPI_Bcast(&record_length,1,MPI_INT,0,IssmComm::GetComm()); 
    393472                                switch(record_code){
    394473                                case 1:
    395474                                        /*boolean. get it from cpu 0 */
    396                                         MPI_Bcast(&booleanint,1,MPI_INT,0,MPI_COMM_WORLD);
    397                                                
     475                                        MPI_Bcast(&booleanint,1,MPI_INT,0,IssmComm::GetComm());
     476
    398477                                        /*create BoolParam: */
    399478                                        this->constants->AddObject(new BoolParam(record_enum,(bool)booleanint)); //cast to a boolean
     
    402481                                case 2:
    403482                                        /*integer. get it from cpu 0 */
    404                                         MPI_Bcast(&integer,1,MPI_INT,0,MPI_COMM_WORLD);
    405                                                
     483                                        MPI_Bcast(&integer,1,MPI_INT,0,IssmComm::GetComm());
     484
    406485                                        /*create IntParam: */
    407486                                        this->constants->AddObject(new IntParam(record_enum,integer));
     
    410489                                case 3:
    411490                                        /*scalar. get it from cpu 0 */
    412                                         MPI_Bcast(&scalar,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
    413                                                
     491                                        MPI_Bcast(&scalar,1,MPI_DOUBLE,0,IssmComm::GetComm());
     492
    414493                                        /*create DoubleParam: */
    415494                                        this->constants->AddObject(new DoubleParam(record_enum,scalar));
     
    417496                                        break;
    418497                                case 4:
    419                                         MPI_Bcast(&string_size,1,MPI_INT,0,MPI_COMM_WORLD);
     498                                        MPI_Bcast(&string_size,1,MPI_INT,0,IssmComm::GetComm());
    420499                                        if(string_size){
    421500                                                string=xNew<char>((string_size+1));
     
    423502
    424503                                                /*Read string from cpu 0: */
    425                                                 MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD);
     504                                                MPI_Bcast(string,string_size,MPI_CHAR,0,IssmComm::GetComm());
    426505                                        }
    427506                                        else{
     
    447526                                }
    448527
    449 
    450528                        }
    451529                }
     
    457535void  IoModel::FetchData(bool* pboolean,int data_enum){
    458536
    459         extern int my_rank;
    460         extern int num_procs;
    461        
     537        int my_rank;
    462538
    463539        /*output: */
    464540        int   booleanint;
    465541        int   code;
    466        
     542
     543        /*recover my_rank:*/
     544        my_rank=IssmComm::GetRank();
     545
    467546        /*Set file pointer to beginning of the data: */
    468547        fid=this->SetFilePointerToData(&code,NULL,data_enum);
    469548
    470549        if(code!=1)_error_("expecting a boolean for enum " << EnumToStringx(data_enum));
    471        
     550
    472551        /*We have to read a boolean from disk. */
    473552        if(my_rank==0){ 
     
    475554        }
    476555        #ifdef _HAVE_MPI_
    477         MPI_Bcast(&booleanint,1,MPI_INT,0,MPI_COMM_WORLD);
     556        MPI_Bcast(&booleanint,1,MPI_INT,0,IssmComm::GetComm());
    478557        #endif
    479558
     
    487566void  IoModel::FetchData(int* pinteger,int data_enum){
    488567
    489         extern int my_rank;
    490         extern int num_procs;
     568        int my_rank;
    491569
    492570        /*output: */
    493571        int   integer;
    494572        int   code;
    495        
     573
     574        /*recover my_rank:*/
     575        my_rank=IssmComm::GetRank();
     576
    496577        /*Set file pointer to beginning of the data: */
    497578        fid=this->SetFilePointerToData(&code,NULL,data_enum);
    498        
     579
    499580        if(code!=2)_error_("expecting an integer for enum " << EnumToStringx(data_enum));
    500        
     581
    501582        /*We have to read a integer from disk. First read the dimensions of the integer, then the integer: */
    502583        if(my_rank==0){ 
     
    505586
    506587        #ifdef _HAVE_MPI_
    507         MPI_Bcast(&integer,1,MPI_INT,0,MPI_COMM_WORLD);
     588        MPI_Bcast(&integer,1,MPI_INT,0,IssmComm::GetComm());
    508589        #endif
    509590
     
    515596void  IoModel::FetchData(IssmDouble* pscalar,int data_enum){
    516597
    517 
    518         extern int my_rank;
    519         extern int num_procs;
    520        
     598        int my_rank;
    521599
    522600        /*output: */
     
    524602        int      code;
    525603
     604        /*recover my_rank:*/
     605        my_rank=IssmComm::GetRank();
     606
    526607        /*Set file pointer to beginning of the data: */
    527608        fid=this->SetFilePointerToData(&code,NULL,data_enum);
    528        
     609
    529610        if(code!=3)_error_("expecting a IssmDouble for enum " << EnumToStringx(data_enum));
    530        
     611
    531612        /*We have to read a scalar from disk. First read the dimensions of the scalar, then the scalar: */
    532613        if(my_rank==0){
     
    534615        }
    535616        #ifdef _HAVE_MPI_
    536         MPI_Bcast(&scalar,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
     617        MPI_Bcast(&scalar,1,MPI_DOUBLE,0,IssmComm::GetComm());
    537618        #endif
    538619
    539620        /*Assign output pointers: */
    540621        *pscalar=scalar;
    541                  
     622
    542623}
    543624/*}}}*/
     
    545626void  IoModel::FetchData(char** pstring,int data_enum){
    546627
    547         extern int my_rank;
    548         extern int num_procs;
    549        
     628        int my_rank;
    550629
    551630        /*output: */
     
    554633        int code=0;
    555634
     635        /*recover my_rank:*/
     636        my_rank=IssmComm::GetRank();
     637
    556638        /*Set file pointer to beginning of the data: */
    557639        fid=this->SetFilePointerToData(&code,NULL,data_enum);
    558        
     640
    559641        if(code!=4)_error_("expecting a string for enum " << EnumToStringx(data_enum));
    560        
     642
    561643        /*Now fetch: */
    562        
     644
    563645        /*We have to read a string from disk. First read the dimensions of the string, then the string: */
    564646        if(my_rank==0){ 
     
    567649
    568650        #ifdef _HAVE_MPI_
    569         MPI_Bcast(&string_size,1,MPI_INT,0,MPI_COMM_WORLD);
     651        MPI_Bcast(&string_size,1,MPI_INT,0,IssmComm::GetComm());
    570652        #endif
    571653
     
    580662                }
    581663                #ifdef _HAVE_MPI_
    582                 MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD);
     664                MPI_Bcast(string,string_size,MPI_CHAR,0,IssmComm::GetComm());
    583665                #endif
    584666        }
     
    588670        }
    589671
    590 
    591672        /*Assign output pointers: */
    592673        *pstring=string;
     
    596677void  IoModel::FetchData(int** pmatrix,int* pM,int* pN,int data_enum){
    597678
    598         extern int my_rank;
    599         extern int num_procs;
     679        int my_rank;
    600680        int i,j;
    601681
     
    607687        int vector_type=0;
    608688
     689        /*recover my_rank:*/
     690        my_rank=IssmComm::GetRank();
    609691
    610692        /*Set file pointer to beginning of the data: */
     
    612694
    613695        if((code!=5) && (code!=6) && (code!=7))_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(data_enum));
    614        
     696
    615697        /*Now fetch: */
    616698
     
    622704
    623705        #ifdef _HAVE_MPI_
    624         MPI_Bcast(&M,1,MPI_INT,0,MPI_COMM_WORLD);
     706        MPI_Bcast(&M,1,MPI_INT,0,IssmComm::GetComm());
    625707        #endif
    626708
     
    629711        }
    630712        #ifdef _HAVE_MPI_
    631         MPI_Bcast(&N,1,MPI_INT,0,MPI_COMM_WORLD);
     713        MPI_Bcast(&N,1,MPI_INT,0,IssmComm::GetComm());
    632714        #endif
    633715
     
    640722                        if(fread(matrix,M*N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read matrix ");
    641723                }
    642                
     724
    643725                #ifdef _HAVE_MPI_
    644                 MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,MPI_COMM_WORLD);
     726                MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,IssmComm::GetComm());
    645727                #endif
    646728        }
     
    671753void  IoModel::FetchData(IssmDouble** pmatrix,int* pM,int* pN,int data_enum){
    672754
    673         extern int my_rank;
    674         extern int num_procs;
     755        int my_rank;
    675756
    676757        /*output: */
     
    680761        int vector_type=0;
    681762
     763        /*recover my_rank:*/
     764        my_rank=IssmComm::GetRank();
     765
    682766        /*Set file pointer to beginning of the data: */
    683767        fid=this->SetFilePointerToData(&code,&vector_type,data_enum);
    684768        if((code!=5) && (code!=6) && (code!=7))_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(data_enum));
    685        
     769
    686770        /*Now fetch: */
    687771
     
    692776        }
    693777        #ifdef _HAVE_MPI_
    694         MPI_Bcast(&M,1,MPI_INT,0,MPI_COMM_WORLD);
     778        MPI_Bcast(&M,1,MPI_INT,0,IssmComm::GetComm());
    695779        #endif
    696780
     
    699783        }
    700784        #ifdef _HAVE_MPI_
    701         MPI_Bcast(&N,1,MPI_INT,0,MPI_COMM_WORLD);
     785        MPI_Bcast(&N,1,MPI_INT,0,IssmComm::GetComm());
    702786        #endif
    703787
     
    711795                }
    712796                #ifdef _HAVE_MPI_
    713                 MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,MPI_COMM_WORLD);
     797                MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,IssmComm::GetComm());
    714798                #endif
    715799
     
    736820void  IoModel::FetchData(char*** pstrings,int* pnumstrings,int data_enum){
    737821
    738         extern int my_rank;
    739         extern int num_procs;
    740        
     822        int my_rank;
     823
    741824        int i;
    742825
     
    744827        int   numstrings=0;
    745828        char** strings=NULL;
    746        
     829
    747830        /*intermediary: */
    748831        char* string=NULL;
    749832        int   string_size;
    750833        int   code;
    751        
     834
     835        /*recover my_rank:*/
     836        my_rank=IssmComm::GetRank();
     837
    752838        /*Set file pointer to beginning of the data: */
    753839        fid=this->SetFilePointerToData(&code,NULL,data_enum);
    754        
     840
    755841        if(code!=9)_error_("expecting a string array for enum " << EnumToStringx(data_enum));
    756        
     842
    757843        /*We have to read a bunch of strings from disk. First read the number of strings, and allocate: */
    758844        if(my_rank==0){ 
     
    760846        }
    761847        #ifdef _HAVE_MPI_
    762         MPI_Bcast(&numstrings,1,MPI_INT,0,MPI_COMM_WORLD);
     848        MPI_Bcast(&numstrings,1,MPI_INT,0,IssmComm::GetComm());
    763849        #endif
    764850
     
    770856                /*Go through strings, and read: */
    771857                for(i=0;i<numstrings;i++){
    772                        
     858
    773859                        if(my_rank==0){ 
    774860                                if(fread(&string_size,sizeof(int),1,fid)!=1) _error_("could not read length of string ");
    775861                        }
    776862                        #ifdef _HAVE_MPI_
    777                         MPI_Bcast(&string_size,1,MPI_INT,0,MPI_COMM_WORLD);
     863                        MPI_Bcast(&string_size,1,MPI_INT,0,IssmComm::GetComm());
    778864                        #endif
    779865                        if(string_size){
     
    786872                                }
    787873                                #ifdef _HAVE_MPI_
    788                                 MPI_Bcast(string,string_size,MPI_CHAR,0,MPI_COMM_WORLD);
     874                                MPI_Bcast(string,string_size,MPI_CHAR,0,IssmComm::GetComm());
    789875                                #endif
    790876                        }
     
    808894        int i;
    809895
    810         extern int my_rank;
    811         extern int num_procs;
     896        int my_rank;
    812897
    813898        /*output: */
     
    821906        IssmPDouble *matrix = NULL;
    822907        int     code;
    823        
     908
     909        /*recover my_rank:*/
     910        my_rank=IssmComm::GetRank();
     911
    824912        /*Set file pointer to beginning of the data: */
    825913        fid=this->SetFilePointerToData(&code,NULL,data_enum);
    826914        if(code!=8)_error_("expecting a IssmDouble mat array for enum " << EnumToStringx(data_enum));
    827        
     915
    828916        /*Now fetch: */
    829917        if(my_rank==0){ 
     
    831919        }
    832920        #ifdef _HAVE_MPI_
    833         MPI_Bcast(&numrecords,1,MPI_INT,0,MPI_COMM_WORLD);
     921        MPI_Bcast(&numrecords,1,MPI_INT,0,IssmComm::GetComm());
    834922        #endif
    835923
     
    854942                        }
    855943                        #ifdef _HAVE_MPI_
    856                         MPI_Bcast(&M,1,MPI_INT,0,MPI_COMM_WORLD);
     944                        MPI_Bcast(&M,1,MPI_INT,0,IssmComm::GetComm());
    857945                        #endif
    858946
     
    861949                        }
    862950                        #ifdef _HAVE_MPI_
    863                         MPI_Bcast(&N,1,MPI_INT,0,MPI_COMM_WORLD);
     951                        MPI_Bcast(&N,1,MPI_INT,0,IssmComm::GetComm());
    864952                        #endif
    865953
     
    874962
    875963                                #ifdef _HAVE_MPI_
    876                                 MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,MPI_COMM_WORLD);
     964                                MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,IssmComm::GetComm());
    877965                                #endif
    878966                                matrices[i]=xNew<IssmDouble>(M*N);
     
    897985/*FUNCTION IoModel::FetchData(Option**  poption,int data_enum){{{*/
    898986void  IoModel::FetchData(Option** poption,int index){
    899 
    900         extern int my_rank;
    901         extern int num_procs;
    902987
    903988        /*output: */
     
    9551040        /*Go through the entire list of enums and fetch the corresponding data. Add it to the iomodel->data dataset. Everything
    9561041         *we fetch is a IssmDouble* : */
    957        
     1042
    9581043        va_start(ap,num);
    9591044        for(i=0; i<num; i++){
    960                
     1045
    9611046                dataenum=va_arg(ap, int);
    962                
     1047
    9631048                if (this->independents[dataenum]){
    9641049                        /*this data has already been checked out! Continue: */
     
    9961081        int     vector_layout = 0;
    9971082        int     counter;
    998         int     nods;
    999         int     nel;
    10001083        int     numberofelements;
    1001 
    10021084
    10031085        /*variables being fetched: */
     
    10231105                        for (i=0;i<numberofelements;i++){
    10241106                                if(this->my_elements[i]){
    1025                                         Element* element=(Element*)elements->GetObjectByOffset(counter);
     1107                                        Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(counter));
    10261108                                        element->InputCreate((IssmDouble)boolean,vector_enum,code);
    10271109                                        counter++;
     
    10361118                        for (i=0;i<numberofelements;i++){
    10371119                                if(this->my_elements[i]){
    1038                                         Element* element=(Element*)elements->GetObjectByOffset(counter);
     1120                                        Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(counter));
    10391121                                        element->InputCreate((IssmDouble)integer,vector_enum,code);
    10401122                                        counter++;
     
    10491131                        for (i=0;i<numberofelements;i++){
    10501132                                if(this->my_elements[i]){
    1051                                         Element* element=(Element*)elements->GetObjectByOffset(counter);
     1133                                        Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(counter));
    10521134                                        element->InputCreate(scalar,vector_enum,code);
    10531135                                        counter++;
     
    10861168                        for (i=0;i<numberofelements;i++){
    10871169                                if(this->my_elements[i]){
    1088                                         Element* element=(Element*)elements->GetObjectByOffset(counter);
     1170                                        Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(counter));
    10891171                                        if(defaulting) element->InputCreate(default_value,vector_enum,code);
    10901172                                        else           element->InputCreate(IssmDoublevector,i,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
     
    11241206                        for (i=0;i<numberofelements;i++){
    11251207                                if(this->my_elements[i]){
    1126                                         Element* element=(Element*)elements->GetObjectByOffset(counter);
     1208                                        Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(counter));
    11271209                                        if(defaulting) element->InputCreate(default_value,vector_enum,code);
    11281210                                        else           element->InputCreate(IssmDoublevector,i,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
     
    11621244                        for (i=0;i<numberofelements;i++){
    11631245                                if(this->my_elements[i]){
    1164                                         Element* element=(Element*)elements->GetObjectByOffset(counter);
     1246                                        Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(counter));
    11651247                                        if(defaulting) element->InputCreate(default_value,vector_enum,code);
    11661248                                        else           element->InputCreate(IssmDoublevector,i,this,M,N,vector_layout,vector_enum,code);//we need i to index into elements.
     
    11831265void IoModel::LastIndex(int *pindex){
    11841266
    1185         extern int my_rank;
     1267        int my_rank;
    11861268        int        lastindex,index;
    11871269        int        record_length;
     1270
     1271        /*recover my_rank:*/
     1272        my_rank=IssmComm::GetRank();
    11881273
    11891274        /*Go find in the binary file, the position of the data we want to fetch: */
     
    12091294        /*Broadcast code and vector type: */
    12101295#ifdef _HAVE_MPI_
    1211         MPI_Bcast(&lastindex,1,MPI_INT,0,MPI_COMM_WORLD);
     1296        MPI_Bcast(&lastindex,1,MPI_INT,0,IssmComm::GetComm());
    12121297#endif
    12131298
     
    12191304FILE* IoModel::SetFilePointerToData(int* pcode,int* pvector_type, int data_enum){
    12201305
    1221         extern int my_rank;
    1222         extern int num_procs;
    1223 
    1224         int found=0;
     1306        int my_rank;
     1307
     1308        int found         = 0;
    12251309        int record_enum;
    12261310        int record_length;
    1227         int record_code; //1 to 7 number
    1228         int vector_type; //nodal or elementary
     1311        int record_code;       //1 to 7 number
     1312        int vector_type   = 0; //nodal or elementary
     1313
     1314        /*recover my_rank:*/
     1315        my_rank=IssmComm::GetRank();
    12291316
    12301317        /*Go find in the binary file, the position of the data we want to fetch: */
     
    12621349                }
    12631350        }
    1264 #ifdef _HAVE_MPI_
    1265         MPI_Bcast(&found,1,MPI_INT,0,MPI_COMM_WORLD);
    1266         if(!found)_error_("could not find data with name" << " " << EnumToStringx(data_enum) << " ");
    1267 #endif
     1351        #ifdef _HAVE_MPI_
     1352        MPI_Bcast(&found,1,MPI_INT,0,IssmComm::GetComm());
     1353        if(!found)_error_("could not find data with name " << EnumToStringx(data_enum) << " in binary file");
     1354        #endif
    12681355
    12691356        /*Broadcast code and vector type: */
    1270 #ifdef _HAVE_MPI_
    1271         MPI_Bcast(&record_code,1,MPI_INT,0,MPI_COMM_WORLD);
    1272         MPI_Bcast(&vector_type,1,MPI_INT,0,MPI_COMM_WORLD);
    1273         if(record_code==5) MPI_Bcast(&vector_type,1,MPI_INT,0,MPI_COMM_WORLD);
    1274 #endif
     1357        #ifdef _HAVE_MPI_
     1358        MPI_Bcast(&record_code,1,MPI_INT,0,IssmComm::GetComm());
     1359        MPI_Bcast(&vector_type,1,MPI_INT,0,IssmComm::GetComm());
     1360        if(record_code==5) MPI_Bcast(&vector_type,1,MPI_INT,0,IssmComm::GetComm());
     1361        #endif
    12751362
    12761363        /*Assign output pointers:*/
     
    12811368}
    12821369/*}}}*/
    1283 /*FUNCTION IoModel::DeclareIndependents{{{*/
    1284 void IoModel::DeclareIndependents(void){
    1285 
    1286         bool autodiff=false;
    1287         int  dummy;
    1288         int i;
    1289         int  num_independents;
    1290         int* independents=NULL;
    1291 
    1292         #ifdef _HAVE_ADOLC_
    1293         /*recover independent enums: */
    1294         this->Constant(&num_independents,AutodiffNumIndependentsEnum);
    1295         if(num_independents){
    1296                 this->FetchData(&independents,&dummy,&dummy,AutodiffIndependentsEnum);
    1297 
    1298                 /*now go fetch the independent variables for each independent enum: */
    1299                 for(i=0;i<num_independents;i++){
    1300                         this->FetchIndependent(independents[i]);
    1301                 }
    1302                 xDelete<int>(independents);
    1303         }
    1304         #else
    1305         /*if we asked for AD computations, we have a problem!: */
    1306         this->Constant(&autodiff,AutodiffIsautodiffEnum);
    1307         if(autodiff)_error_("Cannot carry out AD mode computations without support of ADOLC compiled in!");
    1308         #endif
    1309 
    1310 }
    1311 /*}}}*/
    1312 /*FUNCTION IoModel::FetchIndependent{{{*/
    1313 void IoModel::FetchIndependent(int independent_enum){
    1314 
    1315         #ifdef _HAVE_ADOLC_ //cannot come here unless you are running AD mode, from DeclaredIndependents:
    1316         extern int my_rank;
    1317         extern int num_procs;
    1318 
    1319         /*output: */
    1320         int M,N;
    1321         IssmPDouble* buffer=NULL; //a buffer to read the data from disk
    1322         IssmDouble* matrix=NULL; //our independent variable
    1323         int code=0;
    1324         int vector_type=0;
    1325        
    1326         /*Set file pointer to beginning of the data: */
    1327         fid=this->SetFilePointerToData(&code,&vector_type,independent_enum);
    1328         if((code!=5) && (code!=6) && (code!=7))_error_("expecting a IssmDouble, integer or boolean matrix for enum " << EnumToStringx(independent_enum));
    1329        
    1330         /*Now fetch: */
    1331 
    1332         /*We have to read a matrix from disk. First read the dimensions of the matrix, then the whole matrix: */
    1333         /*numberofelements: */
    1334         if(my_rank==0){ 
    1335                 if(fread(&M,sizeof(int),1,fid)!=1) _error_("could not read number of rows for matrix ");
    1336         }
    1337         #ifdef _HAVE_MPI_
    1338         MPI_Bcast(&M,1,MPI_INT,0,MPI_COMM_WORLD);
    1339         #endif
    1340 
    1341         if(my_rank==0){ 
    1342                 if(fread(&N,sizeof(int),1,fid)!=1) _error_("could not read number of columns for matrix ");
    1343         }
    1344         #ifdef _HAVE_MPI_
    1345         MPI_Bcast(&N,1,MPI_INT,0,MPI_COMM_WORLD);
    1346         #endif
    1347 
    1348         /*Now allocate matrix: */
    1349         if(M*N){
    1350                 buffer=xNew<IssmPDouble>(M*N);
    1351                 matrix=xNew<IssmDouble>(M*N);
    1352 
    1353                 /*Read matrix on node 0, then broadcast: */
    1354                 if(my_rank==0){ 
    1355                         if(fread(buffer,M*N*sizeof(IssmPDouble),1,fid)!=1) _error_("could not read matrix ");
    1356                        
    1357                         /*Now, before we even broadcast this to other nodes, declare the whole matrix as a independent variable!: */
    1358                         for (int i=0;i<M*N;++i) matrix[i]<<=buffer[i];  /*we use the <<= ADOLC overloaded operator to declare the independency*/
    1359                 }
    1360                 #ifdef _HAVE_MPI_
    1361                 MPI_Bcast(matrix,M*N,MPI_DOUBLE,0,MPI_COMM_WORLD);
    1362                 #endif
    1363                
    1364                 xDelete<IssmPDouble>(buffer);
    1365         }
    1366         else _error_("cannot declare the independent variable " << EnumToStringx(independent_enum) <<  "if it's empty!");
    1367 
    1368         /*Ok, we are almost done. Matrix is now a independent matrix. We don't want this matrix to be fetched again in the
    1369          *future, which would effectively write over the independency in the ADOLC tape! So we are going to keep track of this
    1370          independent matrix inthe iomodel->data[independent_enum] data slot: */
    1371         this->data[independent_enum]=matrix;
    1372         this->independents[independent_enum]=true;
    1373         #endif
    1374 }
    1375 /*}}}*/
  • issm/trunk/src/c/classes/IoModel.h

    r13395 r13975  
    1919
    2020        private:
    21                 Parameters  *constants;   //this dataset holds all IssmDouble, int, bool and char *parameters read in from the input file.*
    22        
     21                Parameters *constants;   //this dataset holds all IssmDouble, int, bool and char from input
     22
    2323        public:
    24                 IssmDouble **data;        //this dataset holds temporary data, memory intensive.
    25                
     24                IssmDouble **data;   //this dataset holds temporary data, memory intensive.
     25
    2626                /*This data needs to stay memory resident at all time, even if it's memory intensive: */
    27                 FILE *fid;         //pointer to input file
     27                FILE *fid;                               //pointer to input file
    2828                bool *my_elements;
    2929                bool *my_nodes;
     
    3636                int loadcounter;         //keep track of how many loads are being created in each analysis type
    3737                int constraintcounter;   //keep track of how many constraints are being created in each analysis type
    38                
     38
    3939                /*for AD mode: to keep track of our independent variables we fetch:*/
    4040                bool* independents;
     41                DataSet* independent_objects;
    4142
    4243                /*Methods*/
  • issm/trunk/src/c/classes/Patch.cpp

    r13395 r13975  
    33 */
    44
    5 /*Include files: {{{*/
     5/*Include files */
    66#ifdef HAVE_CONFIG_H
    77        #include <config.h>
     
    1919#include "../shared/shared.h"
    2020#include "../include/include.h"
    21 /*}}}*/
    2221
    2322/*Object constructors and destructors:*/
    2423/*FUNCTION Patch::Patch() default constructor {{{*/
    2524Patch::Patch(){
    26         this->numrows=0;
    27         this->numcols=0;
    28         this->maxvertices=0;
    29         this->maxnodes=0;
    30         this->values=NULL;
     25        this->numrows     = 0;
     26        this->numcols     = 0;
     27        this->maxvertices = 0;
     28        this->maxnodes    = 0;
     29        this->values      = NULL;
    3130}
    3231/*}}}*/
     
    3433Patch::Patch(int in_numrows, int in_maxvertices, int in_maxnodes){
    3534
    36         int i,j;
    3735        this->numrows=in_numrows;
    3836        this->maxvertices=in_maxvertices;
    3937        this->maxnodes=in_maxnodes;
    40    
    4138        this->numcols=1  //enum_type
    4239                +1           //step
     
    5249        }
    5350        else{
    54                 this->values=xNew<IssmDouble>(this->numcols*this->numrows);
    55                 for(i=0;i<this->numrows;i++){
    56                         for(j=0;j<this->numcols;j++){
     51                this->values=xNew<IssmDouble>(this->numcols*this->numrows);
     52                for(int i=0;i<this->numrows;i++){
     53                        for(int j=0;j<this->numcols;j++){
    5754                                this->values[i*this->numcols+j]=NAN;
    5855                        }
     
    9895
    9996        /*Let's remember what is on a row:
    100          enum_type step time element_id interpolation vertices_ids nodal_values
    101          */
     97         enum_type step time element_id interpolation vertices_ids nodal_values */
    10298        row[0]=enum_type;
    10399        row[1]=(IssmDouble)step;
     
    113109void Patch::Gather(void){
    114110
    115         int         i;
    116111        int         count;
    117         extern int  my_rank;
    118         extern int  num_procs;
     112        int         my_rank;
     113        int         num_procs;
    119114        int         total_numrows;
    120115        int         node_numrows;
     
    124119        #endif
    125120
     121        /*recover my_rank:*/
     122        my_rank=IssmComm::GetRank();
     123        num_procs=IssmComm::GetSize();
     124
    126125        /*First, figure out total number of rows combining all the cpus: */
    127126        #ifdef _HAVE_MPI_
    128         MPI_Reduce(&this->numrows,&total_numrows,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
    129         MPI_Bcast(&total_numrows,1,MPI_INT,0,MPI_COMM_WORLD);
     127        MPI_Reduce(&this->numrows,&total_numrows,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
     128        MPI_Bcast(&total_numrows,1,MPI_INT,0,IssmComm::GetComm());
    130129        #else
    131130        total_numrows=this->numrows;
     
    147146        /*Now, ask other nodes to send their values: */
    148147        #ifdef _HAVE_MPI_
    149         for (i=1;i<num_procs;i++){
     148        for(int i=1;i<num_procs;i++){
    150149                if (my_rank==i){
    151                         MPI_Send(&this->numrows,1,MPI_INT,0,1,MPI_COMM_WORLD);   
    152                         if (this->numrows)MPI_Send(this->values,this->numrows*this->numcols,MPI_DOUBLE,0,1,MPI_COMM_WORLD);
     150                        MPI_Send(&this->numrows,1,MPI_INT,0,1,IssmComm::GetComm());   
     151                        if (this->numrows)MPI_Send(this->values,this->numrows*this->numcols,MPI_DOUBLE,0,1,IssmComm::GetComm());
    153152                }
    154153                if (my_rank==0){
    155                         MPI_Recv(&node_numrows,1,MPI_INT,i,1,MPI_COMM_WORLD,&status);
    156                         if (node_numrows)MPI_Recv(total_values+count,node_numrows*this->numcols,MPI_DOUBLE,i,1,MPI_COMM_WORLD,&status);
     154                        MPI_Recv(&node_numrows,1,MPI_INT,i,1,IssmComm::GetComm(),&status);
     155                        if (node_numrows)MPI_Recv(total_values+count,node_numrows*this->numcols,MPI_DOUBLE,i,1,IssmComm::GetComm(),&status);
    157156                        count+=node_numrows*this->numcols;
    158157                }
  • issm/trunk/src/c/classes/Patch.h

    r13395 r13975  
    44
    55/*A Patch object is used to store all results held in elements, in a serial way, and to dump them to disk.
    6        
     6
    77        Each row of the Patch object is made of the following information:
    88        - the result enum_type,
     
    1212        - the vertices ids,
    1313        - and the values at the nodes (could be different from the vertices).
    14        
     14
    1515        For ex:
    1616        1. on a Beam element, Vx, at step 1, time .5, element id 1, interpolation type P0 (constant), vertices ids 1 and 2, one constant value 4.5
     
    1919           VzEnum 2  .8  2 P1  1 3 4     4.5 3.2  2.5
    2020*/
    21 
    2221
    2322#ifndef _PATCH_H_
     
    2928        public:
    3029
    31                 int     numrows; //number of results held in Patch object
    32                 int     numcols; //number of columns
    33                 int     maxvertices; //maxvertices corresponds to largest amount of vertices on a given element, determined by the geometry.
    34                 int     maxnodes;    // maxnodes corresponds to the largest amout of nodes on a given element, determined by the interpolation type.
    35                
    36                 IssmDouble* values;  //result values
     30                int         numrows;       //number of results held in Patch object
     31                int         numcols;       //number of columns
     32                int         maxvertices;   //largest amount of vertices on a given element, determined by geometry
     33                int         maxnodes;      //the largest amout of nodes on a given element, determined by interpolation
     34                IssmDouble *values;        //result values
    3735
    3836                Patch();
  • issm/trunk/src/c/classes/Update.h

    r13395 r13975  
    77
    88/*Headers:*/
    9 /*{{{*/
    109#include "../shared/shared.h"
    11 /*}}}*/
     10class IoModel;
    1211
    1312class Update{
     
    3332
    3433#endif //ifndef _UPDATE_H_
    35 
  • issm/trunk/src/c/classes/bamg/AdjacentTriangle.cpp

    r13395 r13975  
    88
    99namespace bamg {
    10 
    1110
    1211        /*Constructors/Destructors*/
  • issm/trunk/src/c/classes/bamg/AdjacentTriangle.h

    r13395 r13975  
    4444}
    4545#endif
    46 
  • issm/trunk/src/c/classes/bamg/BamgGeom.cpp

    r13395 r13975  
    11#include <stdio.h>
    2 #include "../objects.h"
     2#include "../objects/objects.h"
    33#include "../../io/io.h"
    44#include "../../shared/shared.h"
  • issm/trunk/src/c/classes/bamg/BamgMesh.cpp

    r13395 r13975  
    11#include <stdio.h>
    2 #include "../objects.h"
     2#include "../objects/objects.h"
    33#include "../../io/io.h"
    44#include "../../shared/shared.h"
  • issm/trunk/src/c/classes/bamg/BamgOpts.cpp

    r13395 r13975  
    22#include "../../shared/shared.h"
    33#include "../../include/include.h"
    4 #include "../objects.h"
     4#include "../objects/objects.h"
    55#include "../../io/io.h"
    66
  • issm/trunk/src/c/classes/bamg/BamgQuadtree.cpp

    r13395 r13975  
    33#include <stdlib.h>
    44
    5 #include "../objects.h"
     5#include "../objects/objects.h"
    66
    77namespace bamg {
     
    428428                  }
    429429
    430 
    431430                if ( n0 > 0)
    432431                  { 
  • issm/trunk/src/c/classes/bamg/BamgQuadtree.h

    r13395 r13975  
    3434                                        void    DeepEcho()   {_error_("not implemented yet"); };
    3535                                        int     Id()         {_error_("not implemented yet"); };
    36                                         int     MyRank()     {_error_("not implemented yet"); };
    3736                                        int     ObjectEnum() {_error_("not implemented yet"); };
    3837                                        Object *copy()       {_error_("not implemented yet"); };
  • issm/trunk/src/c/classes/bamg/BamgVertex.cpp

    r13395 r13975  
    44#include <ctime>
    55
    6 #include "../objects.h"
     6#include "../objects/objects.h"
    77
    88namespace bamg {
  • issm/trunk/src/c/classes/bamg/Direction.h

    r13395 r13975  
    1919}
    2020#endif
    21 
  • issm/trunk/src/c/classes/bamg/Edge.h

    r13395 r13975  
    1212        //classes
    1313        class Mesh;
    14        
     14
    1515        class Edge {
    1616
     
    3636}
    3737#endif
    38 
  • issm/trunk/src/c/classes/bamg/EigenMetric.cpp

    r13395 r13975  
    2929                b=-a11-a22;
    3030                delta=b*b - 4*(a11*a22-a21*a21);
    31 
    3231
    3332                /*Compute norm of M to avoid round off errors*/
  • issm/trunk/src/c/classes/bamg/Geometry.cpp

    r13395 r13975  
    44#include <ctime>
    55
    6 #include "../objects.h"
     6#include "../objects/objects.h"
    77#include "../../include/include.h"
    88#include "../../shared/Exceptions/exceptions.h"
     
    6868
    6969                double Hmin = HUGE_VAL;// the infinie value
    70                 int i,j,k,n,i0,i1,i2,i3;
     70                int i,j,n,i0,i1,i2,i3;
    7171
    7272                /*initialize some variables*/
     
    173173                        }
    174174                        delete [] verticeslength;
    175                        
     175
    176176                }
    177177                else{
     
    499499                /*Original code from Frederic Hecht <hecht@ann.jussieu.fr> (BAMG v1.01, MeshGeom.cpp/AfterRead)*/
    500500
    501                 long               i,j,k;
    502                 int                jj;
    503                 long              *head_v   = new long[nbv];
    504                 long              *next_p   = new long[2*nbe];
    505                 float             *eangle   = new float[nbe];
    506                 double             eps      = 1e-20;
    507                 BamgQuadtree           quadtree; // build quadtree to find duplicates
    508                 BamgVertex        *v0       = vertices;
    509                 GeomVertex *v0g      = (GeomVertex*) (void*)v0;
     501                long          i          ,j,k;
     502                long         *head_v   = new long[nbv];
     503                long         *next_p   = new long[2 *nbe];
     504                float        *eangle   = new float[nbe];
     505                double        eps      = 1e-20;
     506                BamgQuadtree  quadtree;                            // build quadtree to find duplicates
     507                BamgVertex   *v0       = vertices;
    510508
    511509                k=0;
     
    869867                directionge[bge]=1;
    870868
    871                 while (eg0!=(GeomEdge*)vg0 && (*eg0)(direction0)!=(GeomVertex*)vg0){
     869                while(eg0!=(GeomEdge*)vg0 && (*eg0)(direction0)!=(GeomVertex*)vg0){
    872870                        if (bge<=0) {
    873871                                if(NbTry) {
     
    904902                        _assert_(tge>=0 && tge<=mxe);
    905903                }
    906 
    907904
    908905                if ((*eg0)(direction0)==(GeomVertex*)vg0)
  • issm/trunk/src/c/classes/bamg/Geometry.h

    r13395 r13975  
    6464                        void             WriteGeometry(BamgGeom *bamggeom, BamgOpts*bamgopts);
    6565        };
    66        
     66
    6767}
    6868#endif
  • issm/trunk/src/c/classes/bamg/ListofIntersectionTriangles.cpp

    r13395 r13975  
    44#include <ctime>
    55
    6 #include "../objects.h"
     6#include "../objects/objects.h"
    77
    88namespace bamg {
     
    319319                                ilast=NewItem(t,ba[0],ba[1],ba[2]); }
    320320                }  //  outside departure
    321 
    322 
    323321
    324322                // recherche the intersection of [a,b] with Bh Mesh.
     
    392390                                Icoor2 detbij = bamg::det((*t)[i],(*t)[j],b);
    393391
    394 
    395392                                if (detbij >= 0) { //we find the triangle contening b
    396393                                        dt[0]=bamg::det((*t)[1],(*t)[2],b);
  • issm/trunk/src/c/classes/bamg/Mesh.cpp

    r13395 r13975  
    44#include <ctime>
    55
    6 #include "../objects.h"
     6#include "../objects/objects.h"
    77
    88namespace bamg {
     
    201201                         }
    202202
    203 
    204203                  if(nbe)
    205204                        edges = new Edge[nbe];
     
    270269                double Hmin = HUGE_VAL;// the infinie value
    271270                long i1,i2,i3;
    272                 long i,j;
     271                long i;
    273272                Metric M1(1);
    274273                int verbose=0;
     
    386385                if(bamgmesh->Quadrilaterals){
    387386                        if(verbose>5) _printLine_("      processing Quadrilaterals");
    388                         long i1,i2,i3,i4,iref;
     387                        long i1,i2,i3,i4;
    389388                        triangles =new Triangle[nbt];
    390389                        for (i=0;i<bamgmesh->QuadrilateralsSize[0];i++){
     
    10091008
    10101009                /*Intermediary*/
    1011                 int i,k,num;
    1012                 int verbose=0;
     1010                int i,k;
    10131011
    10141012                /*output*/
    10151013                int* index=NULL;
     1014                int  num=0;
    10161015
    10171016                /*Get number of triangles*/
     
    10241023                if (k){
    10251024                        index=xNew<int>(3*k);
    1026                         num=0;
    10271025                        for (i=0;i<nbt;i++){
    10281026                                Triangle &t=triangles[i];
     
    12451243                tt[2]->SetSingleVertexToTriangleConnectivity();
    12461244
    1247 
    12481245                // swap if the point s is on a edge
    12491246                if(izerodet>=0) {
     
    15741571                //initialize subdomains[isd].head as 0
    15751572                for (isd=0;isd<nbsubdomains;isd++) subdomains[isd].head =0;
    1576                  
     1573
    15771574                k=0;
    15781575                for (it=0;it<nbt;it++){
     
    25392536                        delete [] HeapArete;
    25402537                        delete [] HeapTriangle;
    2541 
    25422538
    25432539                        if (OutSide|| !Gh.subdomains || !Gh.nbsubdomains )
     
    26952691                                        nbsubdomains=inew;}
    26962692
    2697 
    26982693                                        for (it=0;it<nbt;it++)
    26992694                                         if ( mark[it] ==-1 )
     
    30753070                        if (verbose>5) _printLine_("   do nothing: costheta > 1");
    30763071                }
    3077 
    30783072
    30793073                        long nbqq = (nbt*3)/2;
     
    42734267                        newedges[ie].adj[1]=newedges + ie +1;
    42744268                        R2 A = edges[i][0],B = edges[i][1];
    4275 
    42764269
    42774270                        kk += (i == edge4->SortAndAdd(GetId(edges[i][0]),GetId(edges[i][1])));
     
    43434336                nbv = k;
    43444337
    4345 
    43464338                kedge = new long[3*nbt+1];
    43474339                ksplitarray = new long[nbt+1];
     
    44124404                                const Triangle & tt = ta;
    44134405
    4414 
    44154406                                const BamgVertex & v0 = t[VerticesOfTriangularEdge[j][0]];
    44164407                                const BamgVertex & v1 = t[VerticesOfTriangularEdge[j][1]];
     
    46484639                  BTh.vertices[i].m =  BTh.vertices[i].m*2.;
    46494640
    4650 
    46514641                ret = 2;
    46524642                if (nbt>= maxnbt) goto Error; // bug
     
    49634953
    49644954                /*Intermediaries*/
    4965                 int                i,j,k;
     4955                int                i,k;
    49664956                int                nbcurves    = 0;
    49674957                int                NbNewPoints,NbEdgeCurve;
     
    50014991                                _assert_(nbv<maxnbv);
    50024992                                vertices[nbv]=Gh[i];
    5003                                
     4993
    50044994                                //Add pointer from geometry (Gh) to vertex from mesh (Th)
    50054995                                Gh[i].MeshVertexHook=vertices+nbv;
     
    51965186                                                                                va = vb;
    51975187                                                                        }
    5198                                                                        
     5188
    51995189                                                                        /*We just added one edge to the curve: Go to the next one*/
    52005190                                                                        lcurve = lcurveb;
     
    53715361                                        /*Get curve number*/
    53725362                                        int nc=ei.GeomEdgeHook->CurveNumber;
    5373                                        
     5363
    53745364                                        //_printLine_("Dealing with curve number " << nc);
    53755365                                        //_printLine_("edge on geometry is same as GhCurve? " << (ei.GeomEdgeHook==Gh.curves[nc].FirstEdge || ei.GeomEdgeHook==Gh.curves[nc].LastEdge)?"yes":"no");
     
    54195409                                /*Get edge of Bth with index iedge*/
    54205410                                Edge &ei = BTh.edges[iedge];
    5421                        
     5411
    54225412                                /*Initialize variables*/
    54235413                                double Lstep=0,Lcurve=0;    // step between two points   (phase==1)
     
    55365526                                                }// for(;;) end of the curve
    55375527                                        }
    5538 
    55395528
    55405529                                        if (phase){ // construction of the last edge
     
    57875776                BamgVertex & s2= (*t2)[OppositeVertex[a2]];
    57885777
    5789 
    57905778                Icoor2 dets2 = det(*pva,*pvb,s2);
    57915779                Icoor2 det1=t1->det , det2=t2->det ;
  • issm/trunk/src/c/classes/bamg/Metric.cpp

    r13395 r13975  
    1616        /*FUNCTION Metric::Metric(double a){{{*/
    1717        Metric::Metric(double a): a11(1/(a*a)),a21(0),a22(1/(a*a)){
    18        
     18
    1919        }/*}}}*/
    2020        /*FUNCTION Metric::Metric(double a,double b,double c){{{*/
    2121        Metric::Metric(double a,double b,double c) :a11(a),a21(b),a22(c){
    22        
     22
    2323        }/*}}}*/
    2424        /*FUNCTION Metric::Metric(const double  a[3],const  Metric& m0, const  Metric& m1,const  Metric&  m2 ){{{*/
  • issm/trunk/src/c/classes/bamg/R2.h

    r13395 r13975  
    3939        template <class R,class RR> class P2xP2{
    4040
    41                   private:
    42 
    43                           friend P2<R,RR> operator*(P2<R,RR> c,P2xP2<R,RR> cc){
    44                                   return P2<R,RR>(c.x*cc.x.x + c.y*cc.y.x, c.x*cc.x.y + c.y*cc.y.y);
    45                           }
    4641                  public:
    4742
  • issm/trunk/src/c/classes/bamg/SetOfE4.cpp

    r13395 r13975  
    1 #include "../objects.h"
     1#include "../objects/objects.h"
    22
    33using namespace std;
  • issm/trunk/src/c/classes/bamg/Triangle.cpp

    r13395 r13975  
    44#include <ctime>
    55
    6 #include "../objects.h"
     6#include "../objects/objects.h"
    77
    88namespace bamg {
     
    424424                                                                         sinb12 = double(det2),
    425425                                                                         sinba2 = double(t2->det);
    426 
    427426
    428427                                                 // angle b12 > angle ba2 => cotg(angle b12) < cotg(angle ba2)
  • issm/trunk/src/c/classes/bamg/VertexOnVertex.cpp

    r13395 r13975  
    1717        /*FUNCTION VertexOnVertex::VertexOnVertex(BamgVertex * w,BamgVertex *bw){{{*/
    1818        VertexOnVertex::VertexOnVertex(BamgVertex * w,BamgVertex *bw) :v(w),bv(bw){
    19        
     19
    2020        }/*}}}*/
    2121
  • issm/trunk/src/c/classes/classes.h

    r13395 r13975  
    3030#include "./OptArgs.h"
    3131#include "./OptPars.h"
     32#include "./AdolcEdf.h"
     33#include "./IssmComm.h"
     34#include "./RiftStruct.h"
    3235
    3336#endif
  • issm/trunk/src/c/classes/dakota/DakotaPlugin.cpp

    r13395 r13975  
    1515 */
    1616
    17 
    1817#ifdef HAVE_CONFIG_H
    1918        #include <config.h>
     
    2524#include "../../shared/shared.h"
    2625#include "../../include/include.h"
     26#include "../../solutions/solutions.h"
    2727#include "../classes.h"
    28 #include "../../modules/Dakotax/Dakotax.h"
    2928
    3029/*Standard includes: */
     
    3433
    3534//Dakota headers
    36 #include "DakotaResponse.H"
    37 #include "ParamResponsePair.H"
    38 #include "DakotaPlugin.h"
    39 #include "system_defs.h"
    40 #include "ProblemDescDB.H"
    41 #include "ParallelLibrary.H"
     35#include <DakotaResponse.H>
     36#include <ParamResponsePair.H>
     37#include <system_defs.h>
     38#include <ProblemDescDB.H>
     39#include <ParallelLibrary.H>
     40#include "./DakotaPlugin.h"
    4241
    4342namespace SIM {
    4443
    45 //constructor
    46 DakotaPlugin::DakotaPlugin(const Dakota::ProblemDescDB& problem_db,void* in_femmodel):Dakota::DirectApplicInterface(problem_db){
    47 
     44DakotaPlugin::DakotaPlugin(const Dakota::ProblemDescDB& problem_db,void* in_femmodel):Dakota::DirectApplicInterface(problem_db){/*{{{*/
    4845
    4946        femmodel=in_femmodel;
    5047        counter=0;
    51 }
    52 
    53 //destructor
    54 DakotaPlugin::~DakotaPlugin(){ /* Virtual destructor handles referenceCount at Interface level. */ }
    55 
    56 int DakotaPlugin::derived_map_ac(const Dakota::String& driver) {
     48}/*}}}*/
     49DakotaPlugin::~DakotaPlugin(){/*{{{*/
     50        /* Virtual destructor handles referenceCount at Interface level. */
     51}/*}}}*/
     52int DakotaPlugin::derived_map_ac(const Dakota::String& driver){/*{{{*/
    5753
    5854        int i;
     
    8076                memcpy(variable_descriptor,label.c_str(),(strlen(label.c_str())+1)*sizeof(char));
    8177
    82                
    8378                variable_descriptors[i]=variable_descriptor;
    8479        }
     
    8883
    8984        /*run core solution: */
    90         SpawnCore(responses,numFns, variables,variable_descriptors,numACV,femmodel,counter);
     85        DakotaSpawnCore(responses,numFns, variables,variable_descriptors,numACV,femmodel,counter);
    9186
    9287        /*populate responses: */
     
    9489                fnVals[i]=responses[i];
    9590        }
    96 
    9791
    9892        /*Free ressources:*/
     
    106100
    107101        return 0;
    108 }
    109  
    110 
    111 int DakotaPlugin::GetCounter(){
     102}/*}}}*/
     103int DakotaPlugin::GetCounter(){/*{{{*/
    112104        return counter;
    113 }
     105}/*}}}*/
    114106
    115107} // namespace SIM
    116108
    117 
    118109#endif //only works if dakota library has been compiled in.
  • issm/trunk/src/c/classes/dakota/DakotaPlugin.h

    r13395 r13975  
    55#define _DAKOTAPLUGIN_H
    66
    7 
    87#ifdef _HAVE_DAKOTA_ //only works if dakota library has been compiled in.
    98
    109/*Headers:*/
    11 /*{{{*/
    12 #include "DirectApplicInterface.H"
     10#include <DirectApplicInterface.H>
    1311#include "../../toolkits/toolkits.h"
    1412#include "../../classes/classes.h"
    15 /*}}}*/
    1613
    1714namespace SIM {
     
    4946#endif //only works if dakota library has been compiled in.
    5047
    51 
    5248#endif
  • issm/trunk/src/c/classes/gauss/GaussPenta.h

    r13395 r13975  
    2828                double coord3;
    2929                double coord4;
    30                
     30
    3131        public:
    3232
  • issm/trunk/src/c/classes/gauss/GaussTria.h

    r13395 r13975  
    2525                IssmDouble coord2;
    2626                IssmDouble coord3;
    27                
     27
    2828        public:
    2929
  • issm/trunk/src/c/classes/kriging/ExponentialVariogram.cpp

    r13395 r13975  
    1111#include <stdio.h>
    1212#include <string.h>
    13 #include "../objects.h"
     13#include "../objects/objects.h"
    1414#include "../../EnumDefinitions/EnumDefinitions.h"
    1515#include "../../shared/shared.h"
  • issm/trunk/src/c/classes/kriging/ExponentialVariogram.h

    r13395 r13975  
    2525                void  DeepEcho(){_error_("Not implemented yet");};
    2626                int   Id(){_error_("Not implemented yet");};
    27                 int   MyRank(){_error_("Not implemented yet");};
    2827                int   ObjectEnum(){_error_("Not implemented yet");};
    2928                Object* copy(){_error_("Not implemented yet");};
  • issm/trunk/src/c/classes/kriging/GaussianVariogram.cpp

    r13395 r13975  
    1111#include <stdio.h>
    1212#include <string.h>
    13 #include "../objects.h"
     13#include "../objects/objects.h"
    1414#include "../../EnumDefinitions/EnumDefinitions.h"
    1515#include "../../shared/shared.h"
  • issm/trunk/src/c/classes/kriging/GaussianVariogram.h

    r13395 r13975  
    2626                void  DeepEcho(){_error_("Not implemented yet");};
    2727                int   Id(){_error_("Not implemented yet");};
    28                 int   MyRank(){_error_("Not implemented yet");};
    2928                int   ObjectEnum(){_error_("Not implemented yet");};
    3029                Object* copy(){_error_("Not implemented yet");};
  • issm/trunk/src/c/classes/kriging/Observation.cpp

    r13395 r13975  
    44
    55#include <stdlib.h>
    6 #include "../objects.h"
     6#include "../objects/objects.h"
    77
    88/*Observation constructors and destructor*/
     
    3535void Observation::Echo(void){
    3636
    37         int  bit;
    38 
    3937        _printLine_("Observation");
    4038        _printLine_("   index : " << this->index);
  • issm/trunk/src/c/classes/kriging/Observation.h

    r13395 r13975  
    2626                void    DeepEcho()  {_error_("Not implemented yet"); };
    2727                int     Id()        {_error_("Not implemented yet"); };
    28                 int     MyRank()    {_error_("Not implemented yet"); };
    2928                int     ObjectEnum(){_error_("Not implemented yet"); };
    3029                Object *copy()      {_error_("Not implemented yet"); };
  • issm/trunk/src/c/classes/kriging/PowerVariogram.cpp

    r13395 r13975  
    1111#include <stdio.h>
    1212#include <string.h>
    13 #include "../objects.h"
     13#include "../objects/objects.h"
    1414#include "../../EnumDefinitions/EnumDefinitions.h"
    1515#include "../../shared/shared.h"
  • issm/trunk/src/c/classes/kriging/PowerVariogram.h

    r13395 r13975  
    2525                void  DeepEcho(){_error_("Not implemented yet");};
    2626                int   Id(){_error_("Not implemented yet");};
    27                 int   MyRank(){_error_("Not implemented yet");};
    2827                int   ObjectEnum(){_error_("Not implemented yet");};
    2928                Object* copy(){_error_("Not implemented yet");};
  • issm/trunk/src/c/classes/kriging/Quadtree.cpp

    r13395 r13975  
    1 #include "../objects.h"
     1#include "../objects/objects.h"
    22
    33/*DOCUMENTATION What is a Quadtree? {{{
  • issm/trunk/src/c/classes/kriging/Quadtree.h

    r13395 r13975  
    2929                                void    DeepEcho()  {_error_("not implemented yet"); };
    3030                                int     Id()        {_error_("not implemented yet"); };
    31                                 int     MyRank()    {_error_("not implemented yet"); };
    3231                                int     ObjectEnum(){_error_("not implemented yet"); };
    3332                                Object *copy()      {_error_("not implemented yet"); };
  • issm/trunk/src/c/classes/kriging/SphericalVariogram.cpp

    r13395 r13975  
    1111#include <stdio.h>
    1212#include <string.h>
    13 #include "../objects.h"
     13#include "../objects/objects.h"
    1414#include "../../EnumDefinitions/EnumDefinitions.h"
    1515#include "../../shared/shared.h"
  • issm/trunk/src/c/classes/kriging/SphericalVariogram.h

    r13395 r13975  
    2525                void  DeepEcho(){_error_("Not implemented yet");};
    2626                int   Id(){_error_("Not implemented yet");};
    27                 int   MyRank(){_error_("Not implemented yet");};
    2827                int   ObjectEnum(){_error_("Not implemented yet");};
    2928                Object* copy(){_error_("Not implemented yet");};
  • issm/trunk/src/c/classes/matrix/ElementMatrix.cpp

    r13395 r13975  
    230230/*FUNCTION ElementMatrix::~ElementMatrix(){{{*/
    231231ElementMatrix::~ElementMatrix(){
    232        
     232
    233233        xDelete<IssmDouble>(this->values);
    234234        xDelete<int>(this->gglobaldoflist);
     
    278278                }
    279279
    280 
    281280                if((this->row_ssize!=0) && (this->row_fsize!=0)){
    282281                        /*first, retrieve values that are in the f and s-set from the g-set values matrix: */
  • issm/trunk/src/c/classes/matrix/ElementMatrix.h

    r13395 r13975  
    2222
    2323        public:
    24        
     24
    2525                int      nrows;
    2626                int      ncols;
  • issm/trunk/src/c/classes/matrix/ElementVector.cpp

    r13395 r13975  
    3636        /*intermediaries*/
    3737        int i,j,counter;
    38         int gsize,fsize,ssize;
     38        int gsize,fsize;
    3939        int* P=NULL;
    4040        bool found;
     
    139139        /*fill values with 0: */
    140140        this->values=xNewZeroInit<IssmDouble>(this->nrows);
    141        
     141
    142142        /*g list*/
    143143        this->gglobaldoflist=GetGlobalDofList(nodes,numnodes,GsetEnum,approximation);
     
    151151/*FUNCTION ElementVector::~ElementVector(){{{*/
    152152ElementVector::~ElementVector(){
    153        
     153
    154154        xDelete<IssmDouble>(this->values);
    155155        xDelete<int>(this->gglobaldoflist);
     
    181181                xDelete<IssmDouble>(localvalues);
    182182        }
    183        
     183
    184184}
    185185/*}}}*/
     
    219219void ElementVector::Echo(void){
    220220
    221         int i,j;
     221        int i;
     222
    222223        _printLine_("Element Vector echo:");
    223224        _printLine_("   nrows: " << nrows);
  • issm/trunk/src/c/classes/matrix/ElementVector.h

    r13395 r13975  
    2222
    2323        public:
    24        
     24
    2525                int      nrows;
    2626                IssmDouble*  values;
    27                
     27
    2828                //gset
    2929                int*     gglobaldoflist;
     
    3333                int*     flocaldoflist;
    3434                int*     fglobaldoflist;
    35                
     35
    3636                /*ElementVector constructors, destructors {{{*/
    3737                ElementVector();
     
    5151};
    5252#endif //#ifndef _ELEMENT_VECTOR_H_
    53 
  • issm/trunk/src/c/classes/matrix/Matrix.h

    r13395 r13975  
    7676                }
    7777                /*}}}*/
     78                /*FUNCTION Matrix(int m,int n,int M,int N,int* d_nnz,int* o_nnz,int type){{{*/
     79                #ifdef _HAVE_PETSC_
     80                Matrix(int m,int n,int M,int N,int* d_nnz,int* o_nnz,int in_type=PetscMatType){
     81                #else
     82                Matrix(int m,int n,int M,int N,int* d_nnz,int* o_nnz,int in_type=SeqMatType){
     83                #endif
     84
     85                        #ifdef _HAVE_PETSC_
     86                        pmatrix=NULL;
     87                        #endif
     88                        smatrix=NULL;
     89                        type=in_type;
     90
     91                        if(type==PetscMatType){
     92                                #ifdef _HAVE_PETSC_
     93                                this->pmatrix=new PetscMat(m,n,M,N,d_nnz,o_nnz);
     94                                #else
     95                                _error_("Petsc matrix format not usable, as Petsc has not been compiled!");
     96                                #endif
     97                        }
     98                        else if(type==SeqMatType){
     99                                this->smatrix=new SeqMat<doubletype>(m,n,M,N,d_nnz,o_nnz);
     100                        }
     101                        else _error_("Matrix type: " << type << " not supported yet!");
     102
     103                }
     104                /*}}}*/
    78105                /*FUNCTION Matrix(int M,int N,IssmDouble sparsity,int in_type){{{*/
    79106                #ifdef _HAVE_PETSC_
     
    163190                                #ifdef _HAVE_PETSC_
    164191                                delete this->pmatrix;
    165                                 #else
    166                                 _error_("Petsc matrix format not usable, as Petsc has not been compiled!");
    167192                                #endif
    168193                        }
     
    170195                                delete this->smatrix;
    171196                        }
    172                         else _error_("Matrix type: " << type << " not supported yet!");
    173197
    174198                }
     
    192216                }
    193217                /*}}}*/
     218                /*FUNCTION AllocationInfo{{{*/
     219                void AllocationInfo(void){
     220                        _assert_(this);
     221                        if(type==PetscMatType){
     222                                #ifdef _HAVE_PETSC_
     223                                this->pmatrix->AllocationInfo();
     224                                #endif
     225                        }
     226                        else if(type==SeqMatType){
     227                                //this->smatrix->AllocationInfo();
     228                        }
     229                        else _error_("Matrix type: " << type << " not supported yet!");
     230                }/*}}}*/
    194231                /*FUNCTION Assemble{{{*/
    195232                void Assemble(void){
     
    274311                Matrix* Duplicate(void){
    275312
    276                         Matrix* output=NULL;
    277 
    278                         output=new Matrix();
     313                        Matrix* output=new Matrix();
    279314
    280315                        if(type==PetscMatType){
     
    306341                        else _error_("Matrix type: " << type << " not supported yet!");
    307342
    308 
    309343                        return output;
    310344                }
  • issm/trunk/src/c/classes/matrix/Vector.h

    r13395 r13975  
    6161                        type=in_type;
    6262
    63 
    6463                        if(type==PetscVecType){
    6564                        #ifdef _HAVE_PETSC_
     
    7170                        else if(type==SeqVecType){
    7271                                this->svector=new SeqVec<doubletype>(M,fromlocalsize);
     72                        }
     73                        else _error_("Vector type: " << type << " not supported yet!");
     74
     75                }
     76                /*}}}*/
     77                /*FUNCTION Vector(int m,int M,int in_type){{{*/
     78                #ifdef _HAVE_PETSC_
     79                Vector(int m,int M,int in_type=PetscVecType){
     80                #else
     81                Vector(int m,int M,int in_type=SeqVecType){
     82                #endif
     83
     84                        #ifdef _HAVE_PETSC_
     85                        pvector=NULL;
     86                        #endif
     87                        svector=NULL;
     88                        type=in_type;
     89
     90                        if(type==PetscVecType){
     91                        #ifdef _HAVE_PETSC_
     92                                this->pvector=new PetscVec(m,M);
     93                         #else
     94                                _error_("Petsc matrix format not usable, as Petsc has not been compiled!");
     95                         #endif
     96                        }
     97                        else if(type==SeqVecType){
     98                                this->svector=new SeqVec<doubletype>(m,M);
    7399                        }
    74100                        else _error_("Vector type: " << type << " not supported yet!");
     
    111137                                #ifdef _HAVE_PETSC_
    112138                                delete this->pvector;
    113                                 #else
    114                                 _error_("Petsc matrix format not usable, as Petsc has not been compiled!");
    115139                                #endif
    116140                        }
     
    118142                                delete this->svector;
    119143                        }
    120                         else _error_("Vector type: " << type << " not supported yet!");
    121144                }
    122145                /*}}}*/
     
    171194                void SetValues(int ssize, int* list, doubletype* values, InsMode mode){
    172195
    173 
    174196                        if(type==PetscVecType){
    175197                                #ifdef _HAVE_PETSC_
     
    183205                        }
    184206                        else _error_("Vector type: " << type << " not supported yet!");
    185 
    186 
    187207
    188208                }
     
    207227                /*FUNCTION GetValue{{{*/
    208228                void GetValue(doubletype* pvalue,int dof){
    209 
    210229
    211230                        if(type==PetscVecType){
     
    256275                void GetLocalSize(int* pM){
    257276
    258 
    259277                        if(type==PetscVecType){
    260278                                #ifdef _HAVE_PETSC_
     
    276294                        Vector* output=NULL;
    277295
    278 
    279296                        if(type==PetscVecType){
    280297                                #ifdef _HAVE_PETSC_
     
    298315                void Set(doubletype value){
    299316
    300 
    301317                        if(type==PetscVecType){
    302318                                #ifdef _HAVE_PETSC_
     
    316332                void AXPY(Vector* X, doubletype a){
    317333
    318 
    319334                        if(type==PetscVecType){
    320335                                #ifdef _HAVE_PETSC_
     
    334349                void AYPX(Vector* X, doubletype a){
    335350
    336 
    337351                        if(type==PetscVecType){
    338352                                #ifdef _HAVE_PETSC_
     
    346360                        }
    347361                        else _error_("Vector type: " << type << " not supported yet!");
    348 
    349362
    350363                }
     
    374387                void Copy(Vector* to){
    375388
    376 
    377389                        if(type==PetscVecType){
    378390                                #ifdef _HAVE_PETSC_
     
    386398                        }
    387399                        else _error_("Vector type: " << type << " not supported yet!");
    388 
    389400
    390401                }
     
    413424                void Scale(doubletype scale_factor){
    414425
    415 
    416426                        if(type==PetscVecType){
    417427                                #ifdef _HAVE_PETSC_
     
    451461                void PointwiseDivide(Vector* x,Vector* y){
    452462
    453 
    454463                        if(type==PetscVecType){
    455464                                #ifdef _HAVE_PETSC_
  • issm/trunk/src/c/classes/matrix/matrixobjects.h

    r13395 r13975  
    66#define ALL_MATRIX_OBJECTS_H_
    77
    8 
    98/*Numerics:*/
    109#include "./ElementMatrix.h"
     
    1312#include "./Matrix.h"
    1413
    15 
    1614#endif
  • issm/trunk/src/c/classes/objects/Constraints/Constraint.h

    r13395 r13975  
    44 * It is derived from Object, so DataSets can contain them.
    55 */
    6 
    76
    87#ifndef _CONSTRAINT_H_
     
    1918
    2019        public:
    21                
     20
    2221                virtual      ~Constraint(){};
    2322                virtual void ConstrainNode(Nodes* nodes,Parameters* parameters)=0;
    2423                virtual bool InAnalysis(int analysis_type)=0;
    2524
    26 
    2725};
    2826#endif
  • issm/trunk/src/c/classes/objects/Constraints/SpcDynamic.cpp

    r13395 r13975  
    4141}
    4242/*}}}*/
    43                
     43
    4444/*Object virtual functions definitions:*/
    4545/*FUNCTION SpcDynamic::Echo {{{*/
     
    6565/*FUNCTION SpcDynamic::Id {{{*/
    6666int    SpcDynamic::Id(void){ return sid; }
    67 /*}}}*/
    68 /*FUNCTION SpcDynamic::MyRank {{{*/
    69 int    SpcDynamic::MyRank(void){
    70         extern int my_rank;
    71         return my_rank;
    72 }
    7367/*}}}*/
    7468/*FUNCTION SpcDynamic::ObjectEnum{{{*/
     
    117111/*FUNCTION SpcDynamic::GetNodeId {{{*/
    118112int   SpcDynamic::GetNodeId(){
    119        
     113
    120114        return nodeid;
    121115}
  • issm/trunk/src/c/classes/objects/Constraints/SpcDynamic.h

    r13395 r13975  
    3333                void  DeepEcho();
    3434                int   Id();
    35                 int   MyRank();
    3635                int   ObjectEnum();
    3736                Object* copy();
  • issm/trunk/src/c/classes/objects/Constraints/SpcStatic.cpp

    r13395 r13975  
    4040}
    4141/*}}}*/
    42                
     42
    4343/*Object virtual functions definitions:*/
    4444/*FUNCTION SpcStatic::Echo {{{*/
     
    6868/*FUNCTION SpcStatic::Id {{{*/
    6969int    SpcStatic::Id(void){ return sid; }
    70 /*}}}*/
    71 /*FUNCTION SpcStatic::MyRank {{{*/
    72 int    SpcStatic::MyRank(void){
    73         extern int my_rank;
    74         return my_rank;
    75 }
    7670/*}}}*/
    7771/*FUNCTION SpcStatic::ObjectEnum{{{*/
     
    118112/*FUNCTION SpcStatic::GetNodeId {{{*/
    119113int   SpcStatic::GetNodeId(){
    120        
     114
    121115        return nodeid;
    122116}
  • issm/trunk/src/c/classes/objects/Constraints/SpcStatic.h

    r13395 r13975  
    3232                void  DeepEcho();
    3333                int   Id();
    34                 int   MyRank();
    3534                int   ObjectEnum();
    3635                Object* copy();
  • issm/trunk/src/c/classes/objects/Constraints/SpcTransient.cpp

    r13395 r13975  
    5454}
    5555/*}}}*/
    56                
     56
    5757/*Object virtual functions definitions:*/
    5858/*FUNCTION SpcTransient::Echo {{{*/
     
    8181int    SpcTransient::Id(void){ return sid; }
    8282/*}}}*/
    83 /*FUNCTION SpcTransient::MyRank {{{*/
    84 int    SpcTransient::MyRank(void){
    85         extern int my_rank;
    86         return my_rank;
    87 }
    88 /*}}}*/
    8983/*FUNCTION SpcTransient::ObjectEnum{{{*/
    9084int SpcTransient::ObjectEnum(void){
     
    10397/*FUNCTION SpcTransient::InAnalysis{{{*/
    10498bool SpcTransient::InAnalysis(int in_analysis_type){
    105        
     99
    106100        if (in_analysis_type==this->analysis_type) return true;
    107101        else return false;
     
    120114        /*Chase through nodes and find the node to which this SpcTransient applys: */
    121115        node=(Node*)nodes->GetObjectById(NULL,nodeid);
    122        
     116
    123117        if(node){ //in case the spc is dealing with a node on another cpu
    124118
     
    165159/*FUNCTION SpcTransient::GetNodeId {{{*/
    166160int   SpcTransient::GetNodeId(){
    167        
     161
    168162        return nodeid;
    169163}
     
    174168}
    175169/*}}}*/
    176 
  • issm/trunk/src/c/classes/objects/Constraints/SpcTransient.h

    r13395 r13975  
    3434                void  DeepEcho();
    3535                int   Id();
    36                 int   MyRank();
    3736                int   ObjectEnum();
    3837                Object* copy();
  • issm/trunk/src/c/classes/objects/Contour.h

    r13395 r13975  
    2222        public:
    2323
    24                 int     id;
    25                 int       nods;  //number of vertices in the contour
    26                 doubletype* x;
    27                 doubletype* y;
    28                 bool    closed; //is this contour closed?
     24                int         id;
     25                int         nods;     //number of vertices in the contour
     26                doubletype *x;
     27                doubletype *y;
     28                bool        closed;  //is this contour closed?
    2929
    3030                /*Contour constructors, destructors :*/
    31                 /*FUNCTION Contour() default constructor {{{*/
     31                /*FUNCTION Contour() {{{*/
    3232                Contour(){
    33                         this->id=0;
    34                         this->nods=0;
    35                         this->x=NULL;
    36                         this->y=NULL;
    37                         this->closed=false;
     33                        this->id     = 0;
     34                        this->nods   = 0;
     35                        this->x      = NULL;
     36                        this->y      = NULL;
     37                        this->closed = false;
    3838                }
    3939                /*}}}*/
     
    4141                Contour(int pid,int pnods, doubletype* px, doubletype* py,bool pclosed){
    4242
    43                         this->id=pid;
    44                         this->nods=pnods;
    45                         this->closed=pclosed;
     43                        this->id     = pid;
     44                        this->nods   = pnods;
     45                        this->closed = pclosed;
    4646                        if(nods){
    4747                                this->x=xNew<doubletype>(nods);
     
    5252                }
    5353                /*}}}*/
    54                 /*FUNCTION Contour() default constructor {{{*/
     54                /*FUNCTION ~Contour() {{{*/
    5555                ~Contour(){
    5656                        xDelete<doubletype>(this->x);
     
    5959                /*}}}*/
    6060
    61 
    6261                /*Object virtual function resolutoin: */
    6362                /*FUNCTION Echo(){{{*/
    6463                void Echo(void){
    65 
    66                         int i;
    67 
    68                         _printLine_("Contour: " << id);
    69                         _printLine_("   nods: " << nods);
    70                         _printLine_("   closed: " << (closed?"true":"false"));
     64                        _printLine_(" Contour: " << id);
     65                        _printLine_("    nods: " << nods);
     66                        _printLine_("  closed: " << (closed?"true":"false"));
    7167                        if(nods){
    72                                 _printLine_("   x,y:");
    73                                 for(i=0;i<nods;i++){
    74                                         _printLine_(i << ": " << x[i] << "|" << y[i]);
     68                                _printLine_("   x , y:");
     69                                for(int i=0;i<nods;i++){
     70                                        _printLine_(i << ": " << x[i] << " | " << y[i]);
    7571                                }
    7672                        }
     
    8783                }
    8884                /*}}}*/
    89                 /*FUNCTION MyRank{{{*/
    90                 int    MyRank(void){
    91                         extern int my_rank;
    92 
    93                         return my_rank;
    94                 }
    95                 /*}}}*/
    9685                /*FUNCTION ObjectEnum{{{*/
    9786                int ObjectEnum(void){
    98 
    9987                        return ContourEnum;
    100 
    10188                }
    10289                /*}}}*/
    10390                /*FUNCTION copy {{{*/
    10491                Object* copy() {
    105 
    10692                        return new Contour(*this);
    107 
    10893                }
    10994                /*}}}*/
  • issm/trunk/src/c/classes/objects/ElementResults/BoolElementResult.cpp

    r13395 r13975  
    5858int    BoolElementResult::Id(void){ return -1; }
    5959/*}}}*/
    60 /*FUNCTION BoolElementResult::MyRank{{{*/
    61 int    BoolElementResult::MyRank(void){
    62         extern int my_rank;
    63         return my_rank;
    64 }
    65 /*}}}*/
    6660/*FUNCTION BoolElementResult::ObjectEnum{{{*/
    6761int BoolElementResult::ObjectEnum(void){
     
    116110/*FUNCTION BoolElementResult::PatchFill{{{*/
    117111void BoolElementResult::PatchFill(int row, Patch* patch){
    118        
     112
    119113         /*Here, we fill the result information into the patch object. First, let's remember what is in a row
    120114          * of the patch object: enum_type step time element_id interpolation vertices_ids nodal_values
  • issm/trunk/src/c/classes/objects/ElementResults/BoolElementResult.h

    r13395 r13975  
    33 *  A boll result object is just derived from a BoolInput object, with additional time and step information.
    44 */
    5 
    65
    76#ifndef _BOOLELEMENTRESULT_H_
     
    3433                void  DeepEcho();
    3534                int   Id();
    36                 int   MyRank();
    3735                int   ObjectEnum();
    3836                Object* copy();
  • issm/trunk/src/c/classes/objects/ElementResults/DoubleElementResult.cpp

    r13395 r13975  
    5858int    DoubleElementResult::Id(void){ return -1; }
    5959/*}}}*/
    60 /*FUNCTION DoubleElementResult::MyRank{{{*/
    61 int    DoubleElementResult::MyRank(void){
    62         extern int my_rank;
    63         return my_rank;
    64 }
    65 /*}}}*/
    6660/*FUNCTION DoubleElementResult::ObjectEnum{{{*/
    6761int DoubleElementResult::ObjectEnum(void){
     
    106100/*FUNCTION DoubleElementResult::ProcessUnits{{{*/
    107101void DoubleElementResult::ProcessUnits(Parameters* parameters){
    108        
     102
    109103        this->value=UnitConversion(this->value,IuToExtEnum,this->enum_type);
    110104
     
    118112/*FUNCTION DoubleElementResult::PatchFill{{{*/
    119113void DoubleElementResult::PatchFill(int row, Patch* patch){
    120        
     114
    121115         /*Here, we fill the result information into the patch object. First, let's remember what is in a row
    122116          * of the patch object: enum_type step time element_id interpolation vertices_ids nodal_values
  • issm/trunk/src/c/classes/objects/ElementResults/DoubleElementResult.h

    r13395 r13975  
    33 *  A IssmDouble result object is just derived from a DoubleInput object, with additional time and step information.
    44 */
    5 
    65
    76#ifndef _DOUBLEELEMENTRESULT_H_
     
    3433                void  DeepEcho();
    3534                int   Id();
    36                 int   MyRank();
    3735                int   ObjectEnum();
    3836                Object* copy();
  • issm/trunk/src/c/classes/objects/ElementResults/ElementResult.h

    r13395 r13975  
    22 * \brief abstract class for ElementResult object
    33 */
    4 
    54
    65#ifndef _ELEMENTRESULT_H_
     
    1514
    1615        public:
    17                
     16
    1817                virtual        ~ElementResult(){};
    19                
    2018                virtual         ElementResult* SpawnTriaElementResult(int* indices)=0;
    2119                virtual IssmDouble  GetTime(void)=0;
  • issm/trunk/src/c/classes/objects/ElementResults/ElementResultLocal.h

    r13395 r13975  
    99
    1010#endif //ifndef _ELEMENTRESULTLOCAL_H_
    11 
  • issm/trunk/src/c/classes/objects/ElementResults/PentaP1ElementResult.cpp

    r13395 r13975  
    6161int    PentaP1ElementResult::Id(void){ return -1; }
    6262/*}}}*/
    63 /*FUNCTION PentaP1ElementResult::MyRank{{{*/
    64 int    PentaP1ElementResult::MyRank(void){
    65         extern int my_rank;
    66         return my_rank;
    67 }
    68 /*}}}*/
    6963/*FUNCTION PentaP1ElementResult::ObjectEnum{{{*/
    7064int PentaP1ElementResult::ObjectEnum(void){
     
    7670/*FUNCTION PentaP1ElementResult::copy{{{*/
    7771Object* PentaP1ElementResult::copy() {
    78        
     72
    7973        return new PentaP1ElementResult(this->enum_type,this->values,this->step,this->time);
    8074
     
    117111/*FUNCTION PentaP1ElementResult::ProcessUnits{{{*/
    118112void PentaP1ElementResult::ProcessUnits(Parameters* parameters){
    119        
     113
    120114        UnitConversion(this->values,6,IuToExtEnum,this->enum_type);
    121115
     
    129123/*FUNCTION PentaP1ElementResult::PatchFill{{{*/
    130124void PentaP1ElementResult::PatchFill(int row, Patch* patch){
    131        
     125
    132126         /*Here, we fill the result information into the patch object. First, let's remember what is in a row
    133127          * of the patch object: enum_type step time element_id interpolation vertices_ids nodal_values
  • issm/trunk/src/c/classes/objects/ElementResults/PentaP1ElementResult.h

    r13395 r13975  
    33 *  this object is just a PentaP1Input with additional time and step info.
    44 */
    5 
    65
    76#ifndef _PENTAP1ELEMENTRESULT_H_
     
    3332                void  DeepEcho();
    3433                int   Id();
    35                 int   MyRank();
    3634                int   ObjectEnum();
    3735                Object* copy();
  • issm/trunk/src/c/classes/objects/ElementResults/TriaP1ElementResult.cpp

    r13395 r13975  
    4949/*FUNCTION TriaP1ElementResult::DeepEcho{{{*/
    5050void TriaP1ElementResult::DeepEcho(void){
    51                
     51
    5252        _printLine_("TriaP1ElementResult:");
    5353        _printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
     
    6060int    TriaP1ElementResult::Id(void){ return -1; }
    6161/*}}}*/
    62 /*FUNCTION TriaP1ElementResult::MyRank{{{*/
    63 int    TriaP1ElementResult::MyRank(void){
    64         extern int my_rank;
    65         return my_rank;
    66 }
    67 /*}}}*/
    6862/*FUNCTION TriaP1ElementResult::ObjectEnum{{{*/
    6963int TriaP1ElementResult::ObjectEnum(void){
     
    7569/*FUNCTION TriaP1ElementResult::copy{{{*/
    7670Object* TriaP1ElementResult::copy() {
    77        
     71
    7872        return new TriaP1ElementResult(this->enum_type,this->values,this->step,this->time);
    7973
     
    10599/*FUNCTION TriaP1ElementResult::ProcessUnits{{{*/
    106100void TriaP1ElementResult::ProcessUnits(Parameters* parameters){
    107        
     101
    108102        UnitConversion(this->values,3,IuToExtEnum,this->enum_type);
    109103
     
    117111/*FUNCTION TriaP1ElementResult::PatchFill{{{*/
    118112void TriaP1ElementResult::PatchFill(int row, Patch* patch){
    119        
     113
    120114         /*Here, we fill the result information into the patch object. First, let's remember what is in a row
    121115          * of the patch object: enum_type step time element_id interpolation vertices_ids nodal_values
  • issm/trunk/src/c/classes/objects/ElementResults/TriaP1ElementResult.h

    r13395 r13975  
    22 *  \brief: header file for TriaP1ElementResult object
    33 */
    4 
    54
    65#ifndef _TRIAP1ELEMENTRESULT_H_
     
    3231                void  DeepEcho();
    3332                int   Id();
    34                 int   MyRank();
    3533                int   ObjectEnum();
    3634                Object* copy();
  • issm/trunk/src/c/classes/objects/Elements/Element.h

    r13395 r13975  
    44 * It is derived from Element, so DataSets can contain them.
    55 */
    6 
    76
    87#ifndef _ELEMENT_H_
     
    2524
    2625        public:
    27                
     26
    2827                virtual        ~Element(){};
    29        
     28
    3029                virtual void   Configure(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters)=0;
    3130                virtual void   SetCurrentConfiguration(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters)=0;
     31                virtual void   SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum)=0;
    3232                virtual void   CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>*  Kfs,Vector<IssmDouble>* df)=0;
    3333                virtual void   CreatePVector(Vector<IssmDouble>* pf)=0;
     
    3535                virtual void   GetSolutionFromInputs(Vector<IssmDouble>* solution)=0;
    3636                virtual int    GetNodeIndex(Node* node)=0;
     37                virtual int    GetNumberOfNodes(void)=0;
     38                virtual void   GetNodesSidList(int* sidlist)=0;
     39
    3740                virtual int    Sid()=0;
    3841                virtual bool   IsFloating()=0;
     
    4346                virtual void   GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue)=0;
    4447                virtual void   GetInputValue(IssmDouble* pvalue,Node* node,int enumtype)=0;
    45                
     48
    4649                virtual IssmDouble SurfaceArea(void)=0;
    4750                virtual void   InputDepthAverageAtBase(int enum_type,int average_enum_type,int object_enum)=0;
     
    5962                virtual void   ProcessResultsUnits(void)=0;
    6063                virtual void   RequestedOutput(int output_enum,int step,IssmDouble time)=0;
    61                
     64
    6265                virtual int    NodalValue(IssmDouble* pvalue, int index, int natureofdataenum,bool process_units)=0;
    6366                virtual void   InputScale(int enum_type,IssmDouble scale_factor)=0;
  • issm/trunk/src/c/classes/objects/Elements/Penta.cpp

    r13395 r13975  
    8282        this->inputs=new Inputs();
    8383        this->results=new Results();
    84        
     84
    8585        /*initialize pointers:*/
    8686        this->nodes=NULL;
     
    180180
    181181        /*Intermediaries */
    182         int    count,ig;
     182        int    count;
    183183        IssmDouble basalfriction[NUMVERTICES]={0,0,0,0,0,0};
    184184        IssmDouble alpha2,vx,vy;
    185185        Friction*  friction=NULL;
    186186        GaussPenta* gauss=NULL;
    187 
    188187
    189188        /* Basal friction can only be found at the base of an ice sheet: */
     
    199198        Input* vz_input=inputs->GetInput(VzEnum);                         _assert_(vz_input);
    200199
    201 
    202200        /*Build friction element, needed later: */
    203201        friction=new Friction("3d",inputs,matpar,DiagnosticHorizAnalysisEnum);
     
    206204        gauss=new GaussPenta(0,1,2,2);
    207205        count=0;
    208         for(ig=gauss->begin();ig<gauss->end();ig++){
     206        for(int ig=gauss->begin();ig<gauss->end();ig++){
    209207
    210208                gauss->GaussPoint(ig);
     
    216214                count++;
    217215        }
    218        
     216
    219217        /*Create PentaVertex input, which will hold the basal friction:*/
    220218        this->inputs->AddInput(new PentaP1Input(BasalFrictionEnum,&basalfriction[0]));
     
    228226void  Penta::ComputeBasalStress(Vector<IssmDouble>* sigma_b){
    229227
    230         int         i,j,ig;
     228        int         i,j;
    231229        int         dofv[3]={0,1,2};
    232230        int         dofp[1]={3};
    233231        int         analysis_type,approximation;
    234         int         doflist[NUMVERTICES];
    235         IssmDouble      xyz_list[NUMVERTICES][3];
    236         IssmDouble      xyz_list_tria[3][3];
    237         IssmDouble      rho_ice,gravity,stokesreconditioning;
    238         IssmDouble      pressure,viscosity,bed,Jdet2d;
    239         IssmDouble      bed_normal[3];
    240         IssmDouble      basalforce[3];
    241         IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
    242         IssmDouble      devstresstensor[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
    243         IssmDouble      stresstensor[6]={0.0};
    244         IssmDouble      sigma_xx,sigma_yy,sigma_zz;
    245         IssmDouble      sigma_xy,sigma_xz,sigma_yz;
    246         IssmDouble      surface=0,value=0;
     232        IssmDouble  xyz_list[NUMVERTICES][3];
     233        IssmDouble  xyz_list_tria[3][3];
     234        IssmDouble  rho_ice,gravity,stokesreconditioning;
     235        IssmDouble  pressure,viscosity,Jdet2d;
     236        IssmDouble  bed_normal[3];
     237        IssmDouble  basalforce[3];
     238        IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
     239        IssmDouble  stresstensor[6]={0.0};
     240        IssmDouble  sigma_xx,sigma_yy,sigma_zz;
     241        IssmDouble  sigma_xy,sigma_xz,sigma_yz;
     242        IssmDouble  surface=0,value=0;
    247243        GaussPenta* gauss;
    248244
     
    257253        /*retrieve some parameters: */
    258254        this->parameters->FindParam(&stokesreconditioning,DiagnosticStokesreconditioningEnum);
    259        
     255
    260256        if(!IsOnBed()){
    261257                //put zero
     
    280276        /* Start  looping on the number of gaussian points: */
    281277        gauss=new GaussPenta(0,1,2,2);
    282         for (ig=gauss->begin();ig<gauss->end();ig++){
     278        for(int ig=gauss->begin();ig<gauss->end();ig++){
    283279
    284280                gauss->GaussPoint(ig);
     
    325321void  Penta::ComputeStressTensor(){
    326322
    327         int         iv;
    328323        IssmDouble      xyz_list[NUMVERTICES][3];
    329324        IssmDouble      pressure,viscosity;
     
    364359                sigma_yz[iv]=2*viscosity*epsilon[5];
    365360        }
    366        
     361
    367362        /*Add Stress tensor components into inputs*/
    368363        this->inputs->AddInput(new PentaP1Input(StressTensorxxEnum,&sigma_xx[0]));
     
    381376
    382377        int analysis_counter;
    383        
     378
    384379        /*go into parameters and get the analysis_counter: */
    385380        parametersin->FindParam(&analysis_counter,AnalysisCounterEnum);
     
    421416        _assert_(this->nodes && this->material && this->matpar && this->verticalneighbors && this->parameters && this->inputs);
    422417        /*}}}*/
    423        
     418
    424419        /*Skip if water element*/
    425420        if(IsOnWater()) return;
     
    651646void Penta::DeepEcho(void){
    652647
    653         int i;
    654        
    655648        _printLine_("Penta:");
    656649        _printLine_("   id: " << id);
     
    672665        _printLine_("neighboor sids: ");
    673666        _printLine_(" " << horizontalneighborsids[0] << " " << horizontalneighborsids[1] << " " << horizontalneighborsids[2]);
    674 
    675         return;
    676667}
    677668/*}}}*/
     
    794785void  Penta::GetDofList(int** pdoflist,int approximation_enum,int setenum){
    795786
    796         int  i,j,count=0;
     787        int  i,count=0;
    797788        int  numberofdofs=0;
    798789        int* doflist=NULL;
     
    815806}
    816807/*}}}*/
    817 /*FUNCTION Penta::GetDofList1 {{{*/
    818 void  Penta::GetDofList1(int* doflist){
     808/*FUNCTION Penta::GetVertexPidList {{{*/
     809void  Penta::GetVertexPidList(int* doflist){
    819810
    820811        int i;
    821         for(i=0;i<6;i++) doflist[i]=nodes[i]->GetDofList1();
     812        for(i=0;i<6;i++) doflist[i]=nodes[i]->GetVertexPid();
     813
     814}
     815/*}}}*/
     816/*FUNCTION Penta::GetVertexSidList{{{*/
     817void  Penta::GetVertexSidList(int* sidlist){
     818
     819        int i;
     820        for(i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->GetVertexSid();
    822821
    823822}
     
    892891}
    893892/*}}}*/
     893/*FUNCTION Penta::GetNodesSidList{{{*/
     894void Penta::GetNodesSidList(int* sidlist){
     895
     896        _assert_(sidlist);
     897        _assert_(nodes);
     898
     899        for(int i=0;i<NUMVERTICES;i++){
     900                sidlist[i]=nodes[i]->Sid();
     901        }
     902}
     903/*}}}*/
     904/*FUNCTION Penta::GetNumberOfNodes{{{*/
     905int Penta::GetNumberOfNodes(void){
     906
     907        if(this->nodes==NULL) return 0;
     908
     909        switch(this->element_type){
     910                case P1Enum:
     911                        return 6;
     912                case P1DGEnum:
     913                        return 6;
     914                default:
     915                        _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
     916        }
     917}
     918/*}}}*/
    894919/*FUNCTION Penta::GetInputListOnVertices(IssmDouble* pvalue,int enumtype) {{{*/
    895920void Penta::GetInputListOnVertices(IssmDouble* pvalue,int enumtype){
    896 
    897         /*Intermediaries*/
    898         IssmDouble     value[NUMVERTICES];
    899         GaussPenta *gauss              = NULL;
    900921
    901922        /*Recover input*/
     
    907928
    908929        /* Start looping on the number of vertices: */
    909         gauss=new GaussPenta();
     930        GaussPenta *gauss=new GaussPenta();
    910931        for (int iv=0;iv<NUMVERTICES;iv++){
    911932                gauss->GaussVertex(iv);
     
    920941void Penta::GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue){
    921942
    922         /*Intermediaries*/
    923         IssmDouble     value[NUMVERTICES];
    924         GaussPenta *gauss              = NULL;
    925 
    926943        /*Recover input*/
    927944        Input* input=inputs->GetInput(enumtype);
     
    932949        /* Start looping on the number of vertices: */
    933950        if (input){
    934                 gauss=new GaussPenta();
     951                GaussPenta *gauss=new GaussPenta();
    935952                for (int iv=0;iv<NUMVERTICES;iv++){
    936953                        gauss->GaussVertex(iv);
    937954                        input->GetInputValue(&pvalue[iv],gauss);
    938955                }
     956                delete gauss;
    939957        }
    940958        else{
    941959                for (int iv=0;iv<NUMVERTICES;iv++) pvalue[iv]=defaultvalue;
    942960        }
    943 
    944         /*clean-up*/
    945         delete gauss;
    946961}
    947962/*}}}*/
     
    9951010         *    = 4 * mu * eps_eff ^2*/
    9961011        *phi=4*pow(epsilon_eff,2.0)*viscosity;
    997 }
    998 /*}}}*/
    999 /*FUNCTION Penta::GetSidList{{{*/
    1000 void  Penta::GetSidList(int* sidlist){
    1001 
    1002         int i;
    1003         for(i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->GetSidList();
    1004 
    10051012}
    10061013/*}}}*/
     
    11351142void  Penta::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){
    11361143
    1137         int doflist1[NUMVERTICES];
     1144        int vertexpidlist[NUMVERTICES];
    11381145
    11391146        /*Get out if this is not an element input*/
     
    11411148
    11421149        /*Prepare index list*/
    1143         this->GetDofList1(&doflist1[0]);
     1150        this->GetVertexPidList(&vertexpidlist[0]);
    11441151
    11451152        /*Get input (either in element or material)*/
     
    11481155
    11491156        /*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
    1150         input->GetVectorFromInputs(vector,&doflist1[0]);
     1157        input->GetVectorFromInputs(vector,&vertexpidlist[0]);
    11511158}
    11521159/*}}}*/
     
    11601167        } 
    11611168        if(interp==P1Enum){
    1162                 int doflist1[NUMVERTICES];
     1169                int vertexpidlist[NUMVERTICES];
    11631170                int connectivity[NUMVERTICES];
    1164                 this->GetSidList(&doflist1[0]);
     1171                this->GetVertexSidList(&vertexpidlist[0]);
    11651172                this->GetConnectivityList(&connectivity[0]);
    1166                 elementresult->GetVectorFromResults(vector,&doflist1[0],&connectivity[0],NUMVERTICES);
     1173                elementresult->GetVectorFromResults(vector,&vertexpidlist[0],&connectivity[0],NUMVERTICES);
    11671174        }
    11681175        else if(interp==P0Enum){
     
    11911198/*FUNCTION Penta::Sid {{{*/
    11921199int    Penta::Sid(){
    1193        
     1200
    11941201        return sid;
    11951202
     
    12511258        /*Check that name is an element input*/
    12521259        if (!IsInput(name)) return;
    1253        
     1260
    12541261        if ((code==5) || (code==1)){ //boolean
    12551262                this->inputs->AddInput(new BoolInput(name,reCast<bool,IssmDouble>(scalar)));
     
    12691276
    12701277        /*Intermediaries*/
    1271         int    i,j,t;
     1278        int    i,t;
    12721279        int    penta_vertex_ids[6];
    12731280        int    row;
     
    18731880                penta=penta->GetUpperElement(); _assert_(penta->Id()!=this->id);
    18741881        }
    1875        
     1882
    18761883        /*Free ressources:*/
    18771884        xDelete<int>(doflist);
     
    18971904        /*Add input to the element: */
    18981905        this->inputs->AddInput(new PentaP1Input(enum_type,values));
    1899        
     1906
    19001907        /*Free ressources:*/
    19011908        xDelete<int>(doflist);
     
    19371944                penta=penta->GetUpperElement(); _assert_(penta->Id()!=this->id);
    19381945        }
    1939        
     1946
    19401947        /*Free ressources:*/
    19411948        xDelete<int>(doflist);
     
    19601967                                /*Get values on the 6 vertices*/
    19611968                                for (int i=0;i<6;i++){
    1962                                         values[i]=vector[this->nodes[i]->GetVertexDof()];
     1969                                        values[i]=vector[this->nodes[i]->GetVertexPid()];
    19631970                                }
    19641971
     
    21622169        /*Recover info at the vertices: */
    21632170        parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
     2171        parameters->FindParam(&gl_melting_rate,GroundinglineMeltingRateEnum);
    21642172        parameters->FindParam(&yts,ConstantsYtsEnum);
    21652173        GetInputListOnVertices(&h[0],ThicknessEnum);
     
    21702178        rho_ice=matpar->GetRhoIce();
    21712179        density=rho_ice/rho_water;
    2172        
     2180
    21732181        /*go through vertices, and update inputs, considering them to be PentaVertex type: */
    21742182        for(i=0;i<NUMVERTICES;i++){
     
    22112219                }
    22122220        }
    2213        
     2221
    22142222   /*Add basal melting rate if element just ungrounded*/
    22152223        if(!this->IsFloating() && elementonshelf==true){
     
    22512259
    22522260        return minlength;
    2253 }
    2254 /*}}}*/
    2255 /*FUNCTION Penta::MyRank {{{*/
    2256 int    Penta::MyRank(void){
    2257         extern int my_rank;
    2258         return my_rank;
    22592261}
    22602262/*}}}*/
     
    22992301        /*recover pointer: */
    23002302        count=*pcount;
    2301                
     2303
    23022304        /*will be needed later: */
    23032305        for(i=0;i<6;i++) vertices_ids[i]=nodes[i]->GetVertexId(); //vertices id start at column 3 of the patch.
     
    25082510/*FUNCTION Penta::RequestedOutput{{{*/
    25092511void Penta::RequestedOutput(int output_enum,int step,IssmDouble time){
    2510                        
     2512
    25112513        if(IsInput(output_enum)){
    25122514                /*just transfer this input to results, and we are done: */
     
    26072609}
    26082610/*}}}*/
     2611/*FUNCTION Penta::SetwiseNodeConnectivity{{{*/
     2612void Penta::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
     2613
     2614        /*Output */
     2615        int d_nz = 0;
     2616        int o_nz = 0;
     2617
     2618        /*Loop over all nodes*/
     2619        for(int i=0;i<6;i++){
     2620
     2621                if(!flags[this->nodes[i]->Sid()]){
     2622
     2623                        /*flag current node so that no other element processes it*/
     2624                        flags[this->nodes[i]->Sid()]=true;
     2625
     2626                        /*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
     2627                        switch(set2_enum){
     2628                                case FsetEnum:
     2629                                        if(nodes[i]->indexing.fsize){
     2630                                                if(this->nodes[i]->IsClone())
     2631                                                 o_nz += 1;
     2632                                                else
     2633                                                 d_nz += 1;
     2634                                        }
     2635                                        break;
     2636                                case GsetEnum:
     2637                                        if(nodes[i]->indexing.gsize){
     2638                                                if(this->nodes[i]->IsClone())
     2639                                                 o_nz += 1;
     2640                                                else
     2641                                                 d_nz += 1;
     2642                                        }
     2643                                        break;
     2644                                case SsetEnum:
     2645                                        if(nodes[i]->indexing.ssize){
     2646                                                if(this->nodes[i]->IsClone())
     2647                                                 o_nz += 1;
     2648                                                else
     2649                                                 d_nz += 1;
     2650                                        }
     2651                                        break;
     2652                                default: _error_("not supported");
     2653                        }
     2654                }
     2655        }
     2656
     2657        /*Assign output pointers: */
     2658        *pd_nz=d_nz;
     2659        *po_nz=o_nz;
     2660}
     2661/*}}}*/
    26092662/*FUNCTION Penta::SpawnTria {{{*/
    26102663Tria*  Penta::SpawnTria(int g0, int g1, int g2){
     
    26632716        IssmDouble b_neg[NUMVERTICES];                          // Hs-SMB relation paremeter
    26642717        IssmDouble Hc[NUMVERTICES];                                     // elevation of transition between accumulation regime and ablation regime
     2718        IssmDouble Href[NUMVERTICES];                                   // reference elevation from which deviations are used to calculate the SMB adjustment
     2719        IssmDouble Smbref[NUMVERTICES];                         // reference SMB to which deviations are added
    26652720        IssmDouble smb_pos_max[NUMVERTICES];            // maximum SMB value in the accumulation regime
    26662721        IssmDouble smb_pos_min[NUMVERTICES];            // minimum SMB value in the accumulation regime
     
    26732728        /*Recover SmbGradients*/
    26742729        GetInputListOnVertices(&Hc[0],SurfaceforcingsHcEnum);
     2730        GetInputListOnVertices(&Href[0],SurfaceforcingsHrefEnum);
     2731        GetInputListOnVertices(&Smbref[0],SurfaceforcingsSmbrefEnum);
    26752732        GetInputListOnVertices(&smb_pos_max[0],SurfaceforcingsSmbPosMaxEnum);
    26762733        GetInputListOnVertices(&smb_pos_min[0],SurfaceforcingsSmbPosMinEnum);
     
    26792736        GetInputListOnVertices(&a_neg[0],SurfaceforcingsANegEnum);
    26802737        GetInputListOnVertices(&b_neg[0],SurfaceforcingsBNegEnum);
    2681        
     2738
    26822739   /*Recover surface elevatio at vertices: */
    26832740        GetInputListOnVertices(&h[0],ThicknessEnum);
     
    26872744   rho_ice=matpar->GetRhoIce();
    26882745   rho_water=matpar->GetRhoFreshwater();
    2689                        
     2746
    26902747   // loop over all vertices
    2691    for(i=0;i<NUMVERTICES;i++){
     2748 for(i=0;i<NUMVERTICES;i++){
    26922749     if(s[i]>Hc[i]){
    2693             smb[i]=a_pos[i]+b_pos[i]*s[i];
    2694                  if(smb[i]>smb_pos_max[i]){smb[i]=smb_pos_max[i];}
    2695                  if(smb[i]<smb_pos_min[i]){smb[i]=smb_pos_min[i];}
     2750                  if(Href[i]>Hc[i]){smb[i]=Smbref[i]+b_pos[i]*(s[i]-Href[i]);}
     2751                  if(Href[i]<=Hc[i]){smb[i]=a_pos[i]+b_pos[i]*s[i];}
     2752                  if(smb[i]>smb_pos_max[i]){smb[i]=smb_pos_max[i];}
     2753                  if(smb[i]<smb_pos_min[i]){smb[i]=smb_pos_min[i];}
    26962754          }
    26972755          else{
    2698             smb[i]=a_neg[i]+b_neg[i]*s[i];
     2756                  if(Href[i]>Hc[i]){smb[i]=a_neg[i]+b_neg[i]*s[i];}
     2757                  if(Href[i]<=Hc[i]){smb[i]=Smbref[i]+b_neg[i]*(s[i]-Href[i]);}
    26992758          }
    27002759          smb[i]=smb[i]/rho_ice;      // SMB in m/y ice         
    2701          
    27022760        }  //end of the loop over the vertices
    27032761          /*Update inputs*/
     
    27922850        minz=xyz_list[0][2];
    27932851        maxz=xyz_list[0][2];
    2794        
     2852
    27952853        for(i=1;i<NUMVERTICES;i++){
    27962854                if (xyz_list[i][0]<minx)minx=xyz_list[i][0];
     
    29743032                if (reCast<bool,IssmDouble>(vertices_potentially_ungrounding[nodes[i]->Sid()])){
    29753033                        vec_nodes_on_iceshelf->SetValue(nodes[i]->Sid(),1,INS_VAL);
    2976                
     3034
    29773035                        /*If node was not on ice shelf, we flipped*/
    29783036                        if(nodes_on_iceshelf[nodes[i]->Sid()]==0){
     
    29913049
    29923050        /*Intermediaries*/
    2993         int    iv;
    29943051        IssmDouble phi;
    29953052        IssmDouble viscosity;
    29963053        IssmDouble xyz_list[NUMVERTICES][3];
    29973054        IssmDouble epsilon[6];
    2998         IssmDouble     viscousheating[NUMVERTICES]={0,0,0,0,0,0};
    2999         IssmDouble     thickness;
     3055        IssmDouble viscousheating[NUMVERTICES]={0,0,0,0,0,0};
     3056        IssmDouble thickness;
    30003057        GaussPenta *gauss=NULL;
    30013058
     
    30143071        for (int iv=0;iv<NUMVERTICES;iv++){
    30153072                gauss->GaussVertex(iv);
    3016                
     3073
    30173074                thickness_input->GetInputValue(&thickness,gauss);
    30183075
     
    30203077                material->GetViscosity3dStokes(&viscosity,&epsilon[0]);
    30213078                GetPhi(&phi, &epsilon[0], viscosity);
    3022                
    30233079
    30243080                viscousheating[iv]=phi*thickness;
     
    32753331
    32763332        if(IsOnWater() || !IsOnSurface()) return 0.;
    3277        
     3333
    32783334        GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
    32793335
     
    32873343        smb_input->GetInputAverage(&smb);
    32883344        Total_Smb=rho_ice*base*smb;// smb on element in kg s-1
    3289        
     3345
    32903346        /*Process units: */
    32913347        Total_Smb=UnitConversion(Total_Smb,IuToExtEnum,TotalSmbEnum);// smb on element in GigaTon yr-1
    3292        
     3348
    32933349        /*Return: */
    32943350        return Total_Smb;
     
    33003356/*FUNCTION Penta::CreateKMatrixEnthalpy {{{*/
    33013357ElementMatrix* Penta::CreateKMatrixEnthalpy(void){
    3302        
     3358
    33033359        /*compute all stiffness matrices for this element*/
    33043360        ElementMatrix* Ke1=CreateKMatrixEnthalpyVolume();
    33053361        ElementMatrix* Ke2=CreateKMatrixEnthalpyShelf();
    33063362        ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
    3307        
     3363
    33083364        /*clean-up and return*/
    33093365        delete Ke1;
     
    33203376        /*Intermediaries */
    33213377        int        stabilization;
    3322         int        i,j,ig,found=0;
    3323         IssmDouble     Jdet,u,v,w,um,vm,wm;
    3324         IssmDouble     h,hx,hy,hz,vx,vy,vz,vel;
    3325         IssmDouble     gravity,rho_ice,rho_water;
    3326         IssmDouble     epsvel=2.220446049250313e-16;
    3327         IssmDouble     heatcapacity,thermalconductivity,dt;
    3328         IssmDouble     pressure,enthalpy;
    3329         IssmDouble     latentheat,kappa;
    3330         IssmDouble     tau_parameter,diameter;
    3331         IssmDouble     xyz_list[NUMVERTICES][3];
    3332         IssmDouble     B_conduct[3][numdof];
    3333         IssmDouble     B_advec[3][numdof];
    3334         IssmDouble     Bprime_advec[3][numdof];
    3335         IssmDouble     L[numdof];
    3336         IssmDouble     dbasis[3][6];
    3337         IssmDouble     D_scalar_conduct,D_scalar_advec;
    3338         IssmDouble     D_scalar_trans,D_scalar_stab;
    3339         IssmDouble     D[3][3];
    3340         IssmDouble     K[3][3]={0.0};
     3378        int        i,j,found=0;
     3379        IssmDouble Jdet,u,v,w,um,vm,wm;
     3380        IssmDouble h,hx,hy,hz,vx,vy,vz,vel;
     3381        IssmDouble gravity,rho_ice,rho_water;
     3382        IssmDouble epsvel=2.220446049250313e-16;
     3383        IssmDouble heatcapacity,thermalconductivity,dt;
     3384        IssmDouble pressure,enthalpy;
     3385        IssmDouble latentheat,kappa;
     3386        IssmDouble tau_parameter,diameter;
     3387        IssmDouble xyz_list[NUMVERTICES][3];
     3388        IssmDouble B_conduct[3][numdof];
     3389        IssmDouble B_advec[3][numdof];
     3390        IssmDouble Bprime_advec[3][numdof];
     3391        IssmDouble L[numdof];
     3392        IssmDouble dbasis[3][6];
     3393        IssmDouble D_scalar_conduct,D_scalar_advec;
     3394        IssmDouble D_scalar_trans,D_scalar_stab;
     3395        IssmDouble D[3][3];
     3396        IssmDouble K[3][3]={0.0};
    33413397        Tria*      tria=NULL;
    33423398        GaussPenta *gauss=NULL;
     
    33673423        /* Start  looping on the number of gaussian points: */
    33683424        gauss=new GaussPenta(2,2);
    3369         for (ig=gauss->begin();ig<gauss->end();ig++){
     3425        for(int ig=gauss->begin();ig<gauss->end();ig++){
    33703426
    33713427                gauss->GaussPoint(ig);
     
    34763532
    34773533        /*Intermediaries */
    3478         int       i,j,ig;
    3479         IssmDouble    mixed_layer_capacity,thermal_exchange_velocity;
    3480         IssmDouble    rho_ice,rho_water,heatcapacity;
    3481         IssmDouble    Jdet2d,dt;
    3482         IssmDouble    xyz_list[NUMVERTICES][3];
    3483         IssmDouble      xyz_list_tria[NUMVERTICES2D][3];
    3484         IssmDouble    basis[NUMVERTICES];
    3485         IssmDouble    D_scalar;
     3534        int        i,j;
     3535        IssmDouble mixed_layer_capacity,thermal_exchange_velocity;
     3536        IssmDouble rho_ice,rho_water,heatcapacity;
     3537        IssmDouble Jdet2d,dt;
     3538        IssmDouble xyz_list[NUMVERTICES][3];
     3539        IssmDouble xyz_list_tria[NUMVERTICES2D][3];
     3540        IssmDouble basis[NUMVERTICES];
     3541        IssmDouble D_scalar;
    34863542        GaussPenta *gauss=NULL;
    34873543
     
    35023558        /* Start looping on the number of gauss (nodes on the bedrock) */
    35033559        gauss=new GaussPenta(0,1,2,2);
    3504         for (ig=gauss->begin();ig<gauss->end();ig++){
     3560        for(int ig=gauss->begin();ig<gauss->end();ig++){
    35053561
    35063562                gauss->GaussPoint(ig);
    3507                
     3563
    35083564                GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
    35093565                GetNodalFunctionsP1(&basis[0], gauss);
    3510                                
     3566
    35113567                D_scalar=gauss->weight*Jdet2d*rho_water*mixed_layer_capacity*thermal_exchange_velocity/(rho_ice*heatcapacity);
    35123568                if(reCast<bool,IssmDouble>(dt)) D_scalar=dt*D_scalar;
     
    35173573                                        &Ke->values[0],1);
    35183574        }
    3519        
     3575
    35203576        /*Clean up and return*/
    35213577        delete gauss;
     
    35373593/*FUNCTION Penta::CreateKMatrixThermal {{{*/
    35383594ElementMatrix* Penta::CreateKMatrixThermal(void){
    3539        
     3595
    35403596        /*compute all stiffness matrices for this element*/
    35413597        ElementMatrix* Ke1=CreateKMatrixThermalVolume();
    35423598        ElementMatrix* Ke2=CreateKMatrixThermalShelf();
    35433599        ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
    3544        
     3600
    35453601        /*clean-up and return*/
    35463602        delete Ke1;
     
    35573613        /*Intermediaries */
    35583614        int        stabilization;
    3559         int        i,j,ig,found=0;
    3560         IssmDouble     Jdet,u,v,w,um,vm,wm,vel;
    3561         IssmDouble     h,hx,hy,hz,vx,vy,vz;
    3562         IssmDouble     gravity,rho_ice,rho_water,kappa;
    3563         IssmDouble     heatcapacity,thermalconductivity,dt;
    3564         IssmDouble     tau_parameter,diameter;
    3565         IssmDouble     xyz_list[NUMVERTICES][3];
    3566         IssmDouble     B_conduct[3][numdof];
    3567         IssmDouble     B_advec[3][numdof];
    3568         IssmDouble     Bprime_advec[3][numdof];
    3569         IssmDouble     L[numdof];
    3570         IssmDouble     dbasis[3][6];
    3571         IssmDouble     D_scalar_conduct,D_scalar_advec;
    3572         IssmDouble     D_scalar_trans,D_scalar_stab;
    3573         IssmDouble     D[3][3];
    3574         IssmDouble     K[3][3]={0.0};
     3615        int        i,j,found=0;
     3616        IssmDouble Jdet,u,v,w,um,vm,wm,vel;
     3617        IssmDouble h,hx,hy,hz,vx,vy,vz;
     3618        IssmDouble gravity,rho_ice,rho_water,kappa;
     3619        IssmDouble heatcapacity,thermalconductivity,dt;
     3620        IssmDouble tau_parameter,diameter;
     3621        IssmDouble xyz_list[NUMVERTICES][3];
     3622        IssmDouble B_conduct[3][numdof];
     3623        IssmDouble B_advec[3][numdof];
     3624        IssmDouble Bprime_advec[3][numdof];
     3625        IssmDouble L[numdof];
     3626        IssmDouble dbasis[3][6];
     3627        IssmDouble D_scalar_conduct,D_scalar_advec;
     3628        IssmDouble D_scalar_trans,D_scalar_stab;
     3629        IssmDouble D[3][3];
     3630        IssmDouble K[3][3]={0.0};
    35753631        Tria*      tria=NULL;
    35763632        GaussPenta *gauss=NULL;
     
    35993655        /* Start  looping on the number of gaussian points: */
    36003656        gauss=new GaussPenta(2,2);
    3601         for (ig=gauss->begin();ig<gauss->end();ig++){
     3657        for(int ig=gauss->begin();ig<gauss->end();ig++){
    36023658
    36033659                gauss->GaussPoint(ig);
     
    37043760ElementMatrix* Penta::CreateKMatrixThermalShelf(void){
    37053761
    3706 
    37073762        /*Constants*/
    37083763        const int    numdof=NDOF1*NUMVERTICES;
    37093764
    37103765        /*Intermediaries */
    3711         int       i,j,ig;
    3712         IssmDouble    mixed_layer_capacity,thermal_exchange_velocity;
    3713         IssmDouble    rho_ice,rho_water,heatcapacity;
    3714         IssmDouble    Jdet2d,dt;
    3715         IssmDouble    xyz_list[NUMVERTICES][3];
    3716         IssmDouble      xyz_list_tria[NUMVERTICES2D][3];
    3717         IssmDouble    basis[NUMVERTICES];
    3718         IssmDouble    D_scalar;
     3766        int       i,j;
     3767        IssmDouble mixed_layer_capacity,thermal_exchange_velocity;
     3768        IssmDouble rho_ice,rho_water,heatcapacity;
     3769        IssmDouble Jdet2d,dt;
     3770        IssmDouble xyz_list[NUMVERTICES][3];
     3771        IssmDouble xyz_list_tria[NUMVERTICES2D][3];
     3772        IssmDouble basis[NUMVERTICES];
     3773        IssmDouble D_scalar;
    37193774        GaussPenta *gauss=NULL;
    37203775
     
    37353790        /* Start looping on the number of gauss (nodes on the bedrock) */
    37363791        gauss=new GaussPenta(0,1,2,2);
    3737         for (ig=gauss->begin();ig<gauss->end();ig++){
     3792        for(int ig=gauss->begin();ig<gauss->end();ig++){
    37383793
    37393794                gauss->GaussPoint(ig);
    3740                
     3795
    37413796                GetTriaJacobianDeterminant(&Jdet2d, &xyz_list_tria[0][0], gauss);
    37423797                GetNodalFunctionsP1(&basis[0], gauss);
    3743                                
     3798
    37443799                D_scalar=gauss->weight*Jdet2d*rho_water*mixed_layer_capacity*thermal_exchange_velocity/(heatcapacity*rho_ice);
    37453800                if(reCast<bool,IssmDouble>(dt)) D_scalar=dt*D_scalar;
     
    37503805                                        &Ke->values[0],1);
    37513806        }
    3752        
     3807
    37533808        /*Clean up and return*/
    37543809        delete gauss;
     
    37793834
    37803835        /*Intermediaries*/
    3781         int    i,j,ig,found=0;
     3836        int    i,j,found=0;
    37823837        int    friction_type,stabilization;
    37833838        IssmDouble Jdet,phi,dt;
     
    38223877        /* Start  looping on the number of gaussian points: */
    38233878        gauss=new GaussPenta(2,3);
    3824         for (ig=gauss->begin();ig<gauss->end();ig++){
     3879        for(int ig=gauss->begin();ig<gauss->end();ig++){
    38253880
    38263881                gauss->GaussPoint(ig);
     
    38753930
    38763931        /*Intermediaries */
    3877         int        i,j,ig;
    3878         IssmDouble     Jdet2d;
    3879         IssmDouble     heatcapacity,h_pmp;
    3880         IssmDouble     mixed_layer_capacity,thermal_exchange_velocity;
    3881         IssmDouble     rho_ice,rho_water,pressure,dt,scalar_ocean;
    3882         IssmDouble     xyz_list[NUMVERTICES][3];
    3883         IssmDouble     xyz_list_tria[NUMVERTICES2D][3];
    3884         IssmDouble     basis[NUMVERTICES];
     3932        int        i,j;
     3933        IssmDouble Jdet2d;
     3934        IssmDouble heatcapacity,h_pmp;
     3935        IssmDouble mixed_layer_capacity,thermal_exchange_velocity;
     3936        IssmDouble rho_ice,rho_water,pressure,dt,scalar_ocean;
     3937        IssmDouble xyz_list[NUMVERTICES][3];
     3938        IssmDouble xyz_list_tria[NUMVERTICES2D][3];
     3939        IssmDouble basis[NUMVERTICES];
    38853940        GaussPenta* gauss=NULL;
    38863941
     
    39043959        /* Start looping on the number of gauss 2d (nodes on the bedrock) */
    39053960        gauss=new GaussPenta(0,1,2,2);
    3906         for(ig=gauss->begin();ig<gauss->end();ig++){
     3961        for(int ig=gauss->begin();ig<gauss->end();ig++){
    39073962
    39083963                gauss->GaussPoint(ig);
     
    39323987
    39333988        /*Intermediaries */
    3934         int        i,j,ig;
     3989        int        i,j;
    39353990        int        analysis_type;
    3936         IssmDouble     xyz_list[NUMVERTICES][3];
    3937         IssmDouble     xyz_list_tria[NUMVERTICES2D][3]={0.0};
    3938         IssmDouble     Jdet2d,dt;
    3939         IssmDouble     rho_ice,heatcapacity,geothermalflux_value;
    3940         IssmDouble     basalfriction,alpha2,vx,vy;
    3941         IssmDouble     scalar,enthalpy,enthalpyup;
    3942         IssmDouble     pressure,pressureup;
    3943         IssmDouble     basis[NUMVERTICES];
     3991        IssmDouble xyz_list[NUMVERTICES][3];
     3992        IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
     3993        IssmDouble Jdet2d,dt;
     3994        IssmDouble rho_ice,heatcapacity,geothermalflux_value;
     3995        IssmDouble basalfriction,alpha2,vx,vy;
     3996        IssmDouble scalar,enthalpy,enthalpyup;
     3997        IssmDouble pressure,pressureup;
     3998        IssmDouble basis[NUMVERTICES];
    39443999        Friction*  friction=NULL;
    39454000        GaussPenta* gauss=NULL;
     
    39724027        gauss=new GaussPenta(0,1,2,2);
    39734028        gaussup=new GaussPenta(3,4,5,2);
    3974         for(ig=gauss->begin();ig<gauss->end();ig++){
     4029        for(int ig=gauss->begin();ig<gauss->end();ig++){
    39754030
    39764031                gauss->GaussPoint(ig);
     
    40424097
    40434098        /*Intermediaries*/
    4044         int    i,j,ig,found=0;
     4099        int    i,j,found=0;
    40454100        int    friction_type,stabilization;
    40464101        IssmDouble Jdet,phi,dt;
     
    40784133        /* Start  looping on the number of gaussian points: */
    40794134        gauss=new GaussPenta(2,3);
    4080         for (ig=gauss->begin();ig<gauss->end();ig++){
     4135        for(int ig=gauss->begin();ig<gauss->end();ig++){
    40814136
    40824137                gauss->GaussPoint(ig);
     
    41294184
    41304185        /*Intermediaries */
    4131         int        i,j,ig;
    4132         IssmDouble     Jdet2d;
    4133         IssmDouble     mixed_layer_capacity,thermal_exchange_velocity;
    4134         IssmDouble     rho_ice,rho_water,pressure,dt,scalar_ocean;
    4135         IssmDouble     heatcapacity,t_pmp;
    4136         IssmDouble     xyz_list[NUMVERTICES][3];
    4137         IssmDouble     xyz_list_tria[NUMVERTICES2D][3];
    4138         IssmDouble     basis[NUMVERTICES];
     4186        int        i,j;
     4187        IssmDouble Jdet2d;
     4188        IssmDouble mixed_layer_capacity,thermal_exchange_velocity;
     4189        IssmDouble rho_ice,rho_water,pressure,dt,scalar_ocean;
     4190        IssmDouble heatcapacity,t_pmp;
     4191        IssmDouble xyz_list[NUMVERTICES][3];
     4192        IssmDouble xyz_list_tria[NUMVERTICES2D][3];
     4193        IssmDouble basis[NUMVERTICES];
    41394194        GaussPenta* gauss=NULL;
    41404195
     
    41584213        /* Start looping on the number of gauss 2d (nodes on the bedrock) */
    41594214        gauss=new GaussPenta(0,1,2,2);
    4160         for(ig=gauss->begin();ig<gauss->end();ig++){
     4215        for(int ig=gauss->begin();ig<gauss->end();ig++){
    41614216
    41624217                gauss->GaussPoint(ig);
     
    41864241
    41874242        /*Intermediaries */
    4188         int        i,j,ig;
     4243        int        i,j;
    41894244        int        analysis_type;
    4190         IssmDouble     xyz_list[NUMVERTICES][3];
    4191         IssmDouble     xyz_list_tria[NUMVERTICES2D][3]={0.0};
    4192         IssmDouble     Jdet2d,dt;
    4193         IssmDouble     rho_ice,heatcapacity,geothermalflux_value;
    4194         IssmDouble     basalfriction,alpha2,vx,vy;
    4195         IssmDouble     basis[NUMVERTICES];
    4196         IssmDouble     scalar;
     4245        IssmDouble xyz_list[NUMVERTICES][3];
     4246        IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
     4247        IssmDouble Jdet2d,dt;
     4248        IssmDouble rho_ice,heatcapacity,geothermalflux_value;
     4249        IssmDouble basalfriction,alpha2,vx,vy;
     4250        IssmDouble basis[NUMVERTICES];
     4251        IssmDouble scalar;
    41974252        Friction*  friction=NULL;
    41984253        GaussPenta* gauss=NULL;
     
    42214276        /* Start looping on the number of gauss 2d (nodes on the bedrock) */
    42224277        gauss=new GaussPenta(0,1,2,2);
    4223         for(ig=gauss->begin();ig<gauss->end();ig++){
     4278        for(int ig=gauss->begin();ig<gauss->end();ig++){
    42244279
    42254280                gauss->GaussPoint(ig);
     
    44104465        GetInputListOnVertices(&pressure[0],PressureEnum);
    44114466        Input* surface_input=inputs->GetInput(SurfaceEnum); _assert_(surface_input);
    4412        
     4467
    44134468        this->inputs->GetInputValue(&converged,ConvergedEnum);
    44144469        if(converged){
     
    44194474                        //if(waterfraction[i]>1) _error_("Water fraction >1 found in solution vector");
    44204475                }
    4421                        
     4476
    44224477                this->inputs->AddInput(new PentaP1Input(EnthalpyEnum,values));
    44234478                this->inputs->AddInput(new PentaP1Input(WaterfractionEnum,waterfraction));
     
    44634518void Penta::ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index){
    44644519
    4465         int doflist1[NUMVERTICES];
     4520        int vertexpidlist[NUMVERTICES];
    44664521        Input* input=NULL;
    44674522
     
    44744529                input=(Input*)material->inputs->GetInput(MaterialsRheologyZEnum);
    44754530        }
    4476                
     4531
    44774532        else{
    44784533                input=inputs->GetInput(enum_type);
     
    44814536        if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
    44824537
    4483         GradientIndexing(&doflist1[0],control_index);
    4484         ((ControlInput*)input)->GetGradient(gradient,&doflist1[0]);
     4538        GradientIndexing(&vertexpidlist[0],control_index);
     4539        ((ControlInput*)input)->GetGradient(gradient,&vertexpidlist[0]);
    44854540
    44864541}/*}}}*/
     
    45074562void Penta::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){
    45084563
    4509         int    doflist1[NUMVERTICES];
     4564        int    vertexpidlist[NUMVERTICES];
    45104565        IssmDouble grad_list[NUMVERTICES];
    45114566        Input* grad_input=NULL;
     
    45244579        if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
    45254580
    4526         GradientIndexing(&doflist1[0],control_index);
    4527         for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[doflist1[i]];
     4581        GradientIndexing(&vertexpidlist[0],control_index);
     4582        for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[vertexpidlist[i]];
    45284583        grad_input=new PentaP1Input(GradientEnum,grad_list);
    45294584        ((ControlInput*)input)->SetGradient(grad_input);
     
    45874642ElementMatrix* Penta::CreateKMatrixAdjointPattyn(void){
    45884643
    4589         /*Constants*/
    4590         const int    numdof=NDOF2*NUMVERTICES;
    4591 
    45924644        /*Intermediaries */
    4593         int        i,j,ig;
     4645        int        i,j;
    45944646        bool       incomplete_adjoint;
    4595         IssmDouble     xyz_list[NUMVERTICES][3];
    4596         IssmDouble     Jdet;
    4597         IssmDouble     eps1dotdphii,eps1dotdphij;
    4598         IssmDouble     eps2dotdphii,eps2dotdphij;
    4599         IssmDouble     mu_prime;
    4600         IssmDouble     epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
    4601         IssmDouble     eps1[3],eps2[3];
    4602         IssmDouble     phi[NUMVERTICES];
    4603         IssmDouble     dphi[3][NUMVERTICES];
     4647        IssmDouble xyz_list[NUMVERTICES][3];
     4648        IssmDouble Jdet;
     4649        IssmDouble eps1dotdphii,eps1dotdphij;
     4650        IssmDouble eps2dotdphii,eps2dotdphij;
     4651        IssmDouble mu_prime;
     4652        IssmDouble epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
     4653        IssmDouble eps1[3],eps2[3];
     4654        IssmDouble phi[NUMVERTICES];
     4655        IssmDouble dphi[3][NUMVERTICES];
    46044656        GaussPenta *gauss=NULL;
    46054657
     
    46164668        /* Start  looping on the number of gaussian points: */
    46174669        gauss=new GaussPenta(5,5);
    4618         for (ig=gauss->begin();ig<gauss->end();ig++){
     4670        for(int ig=gauss->begin();ig<gauss->end();ig++){
    46194671
    46204672                gauss->GaussPoint(ig);
     
    46594711
    46604712        /*Intermediaries */
    4661         int        i,j,ig;
     4713        int        i,j;
    46624714        bool       incomplete_adjoint;
    4663         IssmDouble     xyz_list[NUMVERTICES][3];
    4664         IssmDouble     Jdet;
    4665         IssmDouble     eps1dotdphii,eps1dotdphij;
    4666         IssmDouble     eps2dotdphii,eps2dotdphij;
    4667         IssmDouble     eps3dotdphii,eps3dotdphij;
    4668         IssmDouble     mu_prime;
    4669         IssmDouble     epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
    4670         IssmDouble     eps1[3],eps2[3],eps3[3];
    4671         IssmDouble     phi[NUMVERTICES];
    4672         IssmDouble     dphi[3][NUMVERTICES];
     4715        IssmDouble xyz_list[NUMVERTICES][3];
     4716        IssmDouble Jdet;
     4717        IssmDouble eps1dotdphii,eps1dotdphij;
     4718        IssmDouble eps2dotdphii,eps2dotdphij;
     4719        IssmDouble eps3dotdphii,eps3dotdphij;
     4720        IssmDouble mu_prime;
     4721        IssmDouble epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
     4722        IssmDouble eps1[3],eps2[3],eps3[3];
     4723        IssmDouble dphi[3][NUMVERTICES];
    46734724        GaussPenta *gauss=NULL;
    46744725
     
    46864737        /* Start  looping on the number of gaussian points: */
    46874738        gauss=new GaussPenta(5,5);
    4688         for (ig=gauss->begin();ig<gauss->end();ig++){
     4739        for(int ig=gauss->begin();ig<gauss->end();ig++){
    46894740
    46904741                gauss->GaussPoint(ig);
     
    48024853        /*get gradient indices*/
    48034854        for(int i=0;i<NUMVERTICES;i++){
    4804                 indexing[i]=num_controls*this->nodes[i]->GetVertexDof() + control_index;
     4855                indexing[i]=num_controls*this->nodes[i]->GetVertexPid() + control_index;
    48054856        }
    48064857
     
    49134964void  Penta::GradjDragPattyn(Vector<IssmDouble>* gradient,int control_index){
    49144965
    4915         int        i,j,ig;
     4966        int        i,j;
    49164967        int        analysis_type;
    4917         int        doflist1[NUMVERTICES];
    4918         IssmDouble     vx,vy,lambda,mu,alpha_complement,Jdet;
    4919         IssmDouble     bed,thickness,Neff,drag;
    4920         IssmDouble     xyz_list[NUMVERTICES][3];
    4921         IssmDouble     xyz_list_tria[NUMVERTICES2D][3]={0.0};
    4922         IssmDouble     dk[NDOF3];
    4923         IssmDouble     grade_g[NUMVERTICES]={0.0};
    4924         IssmDouble     grade_g_gaussian[NUMVERTICES];
    4925         IssmDouble     basis[6];
     4968        int        vertexpidlist[NUMVERTICES];
     4969        IssmDouble vx,vy,lambda,mu,alpha_complement,Jdet;
     4970        IssmDouble bed,thickness,Neff,drag;
     4971        IssmDouble xyz_list[NUMVERTICES][3];
     4972        IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
     4973        IssmDouble dk[NDOF3];
     4974        IssmDouble grade_g[NUMVERTICES]={0.0};
     4975        IssmDouble grade_g_gaussian[NUMVERTICES];
     4976        IssmDouble basis[6];
    49264977        Friction*  friction=NULL;
    4927         GaussPenta  *gauss=NULL;
     4978        GaussPenta *gauss=NULL;
    49284979
    49294980        /*Gradient is 0 if on shelf or not on bed*/
     
    49324983        /*Retrieve all inputs and parameters*/
    49334984        parameters->FindParam(&analysis_type,AnalysisTypeEnum);
    4934         GradientIndexing(&doflist1[0],control_index);
     4985        GradientIndexing(&vertexpidlist[0],control_index);
    49354986        GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
    49364987        for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<2;j++) xyz_list_tria[i][j]=xyz_list[i][j];
     
    49464997        /* Start  looping on the number of gaussian points: */
    49474998        gauss=new GaussPenta(0,1,2,4);
    4948         for (ig=gauss->begin();ig<gauss->end();ig++){
     4999        for(int ig=gauss->begin();ig<gauss->end();ig++){
    49495000
    49505001                gauss->GaussPoint(ig);
     
    49745025                }
    49755026        }
    4976         gradient->SetValues(NUMVERTICES,doflist1,grade_g,ADD_VAL);
     5027        gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
    49775028
    49785029        /*Clean up and return*/
     
    49845035void  Penta::GradjDragStokes(Vector<IssmDouble>* gradient,int control_index){
    49855036
    4986         int        i,j,ig;
     5037        int        i,j;
    49875038        int        analysis_type;
    4988         int        doflist1[NUMVERTICES];
    4989         IssmDouble     bed,thickness,Neff;
    4990         IssmDouble     lambda,mu,xi,Jdet,vx,vy,vz;
    4991         IssmDouble     alpha_complement,drag;
    4992         IssmDouble     surface_normal[3],bed_normal[3];
    4993         IssmDouble     xyz_list[NUMVERTICES][3];
    4994         IssmDouble     xyz_list_tria[NUMVERTICES2D][3]={0.0};
    4995         IssmDouble     dk[NDOF3];
    4996         IssmDouble     basis[6];
    4997         IssmDouble     grade_g[NUMVERTICES]={0.0};
    4998         IssmDouble     grade_g_gaussian[NUMVERTICES];
     5039        int        vertexpidlist[NUMVERTICES];
     5040        IssmDouble bed,thickness,Neff;
     5041        IssmDouble lambda,mu,xi,Jdet,vx,vy,vz;
     5042        IssmDouble alpha_complement,drag;
     5043        IssmDouble surface_normal[3],bed_normal[3];
     5044        IssmDouble xyz_list[NUMVERTICES][3];
     5045        IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
     5046        IssmDouble dk[NDOF3];
     5047        IssmDouble basis[6];
     5048        IssmDouble grade_g[NUMVERTICES]={0.0};
     5049        IssmDouble grade_g_gaussian[NUMVERTICES];
    49995050        Friction*  friction=NULL;
    50005051        GaussPenta* gauss=NULL;
     
    50075058        GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
    50085059        for(i=0;i<NUMVERTICES2D;i++) for(j=0;j<2;j++) xyz_list_tria[i][j]=xyz_list[i][j];
    5009         GradientIndexing(&doflist1[0],control_index);
     5060        GradientIndexing(&vertexpidlist[0],control_index);
    50105061        Input* drag_input    =inputs->GetInput(FrictionCoefficientEnum); _assert_(drag_input);
    50115062        Input* vx_input      =inputs->GetInput(VxEnum);                  _assert_(vx_input);
     
    50215072        /* Start  looping on the number of gaussian points: */
    50225073        gauss=new GaussPenta(0,1,2,4);
    5023         for(ig=gauss->begin();ig<gauss->end();ig++){
     5074        for(int ig=gauss->begin();ig<gauss->end();ig++){
    50245075
    50255076                gauss->GaussPoint(ig);
     
    50675118        }
    50685119
    5069         gradient->SetValues(NUMVERTICES,doflist1,grade_g,ADD_VAL);
     5120        gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
    50705121
    50715122        delete friction;
     
    54945545void  Penta::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data){
    54955546
    5496         int doflist1[NUMVERTICES];
     5547        int vertexpidlist[NUMVERTICES];
    54975548
    54985549        /*Get out if this is not an element input*/
     
    55005551
    55015552        /*Prepare index list*/
    5502         GradientIndexing(&doflist1[0],control_index);
     5553        GradientIndexing(&vertexpidlist[0],control_index);
    55035554
    55045555        /*Get input (either in element or material)*/
     
    55115562        }
    55125563
    5513         ((ControlInput*)input)->GetVectorFromInputs(vector,&doflist1[0],data);
     5564        ((ControlInput*)input)->GetVectorFromInputs(vector,&vertexpidlist[0],data);
    55145565}
    55155566/*}}}*/
     
    55185569
    55195570        IssmDouble  values[NUMVERTICES];
    5520         int     doflist1[NUMVERTICES];
     5571        int     vertexpidlist[NUMVERTICES];
    55215572        Input  *input     = NULL;
    55225573        Input  *new_input = NULL;
     
    55265577
    55275578        /*Prepare index list*/
    5528         GradientIndexing(&doflist1[0],control_index);
     5579        GradientIndexing(&vertexpidlist[0],control_index);
    55295580
    55305581        /*Get values on vertices*/
    55315582        for (int i=0;i<NUMVERTICES;i++){
    5532                 values[i]=vector[doflist1[i]];
     5583                values[i]=vector[vertexpidlist[i]];
    55335584        }
    55345585        new_input = new PentaP1Input(control_enum,values);
    5535 
    55365586
    55375587        if(control_enum==MaterialsRheologyBbarEnum){
     
    55545604/*FUNCTION Penta::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);{{{*/
    55555605void  Penta::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
    5556        
     5606
    55575607        int i,j;
    55585608
     
    55695619                        /*Get values on the 6 vertices*/
    55705620                        for (i=0;i<6;i++){
    5571                                 values[i]=vector[this->nodes[i]->GetSidList()]; //careful, vector of values here is not parallel distributed, but serial distributed (from a serial Dakota core!)
     5621                                values[i]=vector[this->nodes[i]->GetVertexSid()]; //careful, vector of values here is not parallel distributed, but serial distributed (from a serial Dakota core!)
    55725622                        }
    55735623
     
    55815631                                        IssmDouble  surface[6];
    55825632                                        IssmDouble  bed[6];
    5583                                        
     5633
    55845634                                        /*retrieve inputs: */
    55855635                                        GetInputListOnVertices(&thickness_init[0],ThicknessEnum);
     
    56665716/*FUNCTION Penta::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type);{{{*/
    56675717void  Penta::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){
    5668        
     5718
    56695719        int i,j,t;
    56705720        TransientInput* transientinput=NULL;
     
    56805730
    56815731                case VertexEnum:
    5682                        
     5732
    56835733                        /*Create transient input: */
    5684                                                
     5734
    56855735                        parameters->FindParam(&yts,ConstantsYtsEnum);
    56865736
     
    56895739                                /*create input values: */
    56905740                                for(i=0;i<6;i++){
    5691                                         row=this->nodes[i]->GetSidList();
     5741                                        row=this->nodes[i]->GetVertexSid();
    56925742                                        values[i]=(IssmDouble)matrix[ncols*row+t];
    56935743                                }
     
    57535803/*FUNCTION Penta::CreateKMatrixCouplingMacAyealPattyn{{{*/
    57545804ElementMatrix* Penta::CreateKMatrixCouplingMacAyealPattyn(void){
    5755        
     5805
    57565806        /*compute all stiffness matrices for this element*/
    57575807        ElementMatrix* Ke1=CreateKMatrixCouplingMacAyealPattynViscous();
    57585808        ElementMatrix* Ke2=CreateKMatrixCouplingMacAyealPattynFriction();
    57595809        ElementMatrix* Ke=new ElementMatrix(Ke1,Ke2);
    5760        
     5810
    57615811        /*clean-up and return*/
    57625812        delete Ke1;
     
    57755825
    57765826        /*Intermediaries */
    5777         int         i,j,ig;
    5778         IssmDouble      Jdet;
    5779         IssmDouble      viscosity,oldviscosity,newviscosity,viscosity_overshoot; //viscosity
    5780         IssmDouble      epsilon[5],oldepsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
    5781         IssmDouble      xyz_list[NUMVERTICES][3];
    5782         IssmDouble      B[3][numdofp];
    5783         IssmDouble      Bprime[3][numdofm];
    5784         IssmDouble      D[3][3]={0.0};            // material matrix, simple scalar matrix.
    5785         IssmDouble      D_scalar;
    5786         IssmDouble      Ke_gg[numdofp][numdofm]={0.0}; //local element stiffness matrix
    5787         IssmDouble      Ke_gg_gaussian[numdofp][numdofm]; //stiffness matrix evaluated at the gaussian point.
     5827        int         i,j;
     5828        IssmDouble  Jdet;
     5829        IssmDouble  viscosity,oldviscosity,newviscosity,viscosity_overshoot; //viscosity
     5830        IssmDouble  epsilon[5],oldepsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
     5831        IssmDouble  xyz_list[NUMVERTICES][3];
     5832        IssmDouble  B[3][numdofp];
     5833        IssmDouble  Bprime[3][numdofm];
     5834        IssmDouble  D[3][3]={0.0};            // material matrix, simple scalar matrix.
     5835        IssmDouble  D_scalar;
     5836        IssmDouble  Ke_gg[numdofp][numdofm]={0.0}; //local element stiffness matrix
     5837        IssmDouble  Ke_gg_gaussian[numdofp][numdofm]; //stiffness matrix evaluated at the gaussian point.
    57885838        GaussPenta *gauss=NULL;
    57895839        GaussTria  *gauss_tria=NULL;
     
    58205870        gauss=new GaussPenta(5,5);
    58215871        gauss_tria=new GaussTria();
    5822         for (ig=gauss->begin();ig<gauss->end();ig++){
     5872        for(int ig=gauss->begin();ig<gauss->end();ig++){
    58235873
    58245874                gauss->GaussPoint(ig);
     
    58655915        const int numdof      = NDOF2 *NUMVERTICES;
    58665916        const int numdoftotal = NDOF4 *NUMVERTICES;
    5867        
     5917
    58685918        /*Intermediaries */
    5869         int       i,j,ig,analysis_type;
    5870         IssmDouble    Jdet2d,slope_magnitude,alpha2;
    5871         IssmDouble    xyz_list[NUMVERTICES][3];
    5872         IssmDouble    xyz_list_tria[NUMVERTICES2D][3]={0.0};
    5873         IssmDouble    slope[3]={0.0,0.0,0.0};
    5874         IssmDouble    MAXSLOPE=.06; // 6 %
    5875         IssmDouble    MOUNTAINKEXPONENT=10;
    5876         IssmDouble    L[2][numdof];
    5877         IssmDouble    DL[2][2]                  ={{ 0,0 },{0,0}}; //for basal drag
    5878         IssmDouble    DL_scalar;
    5879         IssmDouble    Ke_gg[numdof][numdof]     ={0.0};
    5880         IssmDouble    Ke_gg_gaussian[numdof][numdof]; //stiffness matrix contribution from drag
     5919        int       i,j,analysis_type;
     5920        IssmDouble Jdet2d,slope_magnitude,alpha2;
     5921        IssmDouble xyz_list[NUMVERTICES][3];
     5922        IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
     5923        IssmDouble slope[3]={0.0,0.0,0.0};
     5924        IssmDouble MAXSLOPE=.06; // 6 %
     5925        IssmDouble MOUNTAINKEXPONENT=10;
     5926        IssmDouble L[2][numdof];
     5927        IssmDouble DL[2][2]                  ={{ 0,0 },{0,0}}; //for basal drag
     5928        IssmDouble DL_scalar;
     5929        IssmDouble Ke_gg[numdof][numdof]     ={0.0};
     5930        IssmDouble Ke_gg_gaussian[numdof][numdof]; //stiffness matrix contribution from drag
    58815931        Friction  *friction = NULL;
    58825932        GaussPenta *gauss=NULL;
     
    59135963        /* Start  looping on the number of gaussian points: */
    59145964        gauss=new GaussPenta(0,1,2,2);
    5915         for (ig=gauss->begin();ig<gauss->end();ig++){
     5965        for(int ig=gauss->begin();ig<gauss->end();ig++){
    59165966
    59175967                gauss->GaussPoint(ig);
     
    59345984                DL_scalar=alpha2*gauss->weight*Jdet2d;
    59355985                for (i=0;i<2;i++) DL[i][i]=DL_scalar;
    5936                
     5986
    59375987                /*  Do the triple producte tL*D*L: */
    59385988                TripleMultiply( &L[0][0],2,numdof,1,
     
    59806030
    59816031        /*Intermediaries */
    5982         int         i,j,ig;
    5983         IssmDouble      Jdet;
    5984         IssmDouble      viscosity,stokesreconditioning; //viscosity
    5985         IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
    5986         IssmDouble      xyz_list[NUMVERTICES][3];
    5987         IssmDouble      B[4][numdofs+3];
    5988         IssmDouble      Bprime[4][numdofm];
    5989         IssmDouble      B2[3][numdofm];
    5990         IssmDouble      Bprime2[3][numdofs+3];
    5991         IssmDouble      D[4][4]={0.0};            // material matrix, simple scalar matrix.
    5992         IssmDouble      D2[3][3]={0.0};            // material matrix, simple scalar matrix.
    5993         IssmDouble      D_scalar;
    5994         IssmDouble      Ke_gg[numdofs][numdofm]={0.0}; //local element stiffness matrix
    5995         IssmDouble      Ke_gg2[numdofm][numdofs]={0.0}; //local element stiffness matrix
    5996         IssmDouble      Ke_gg_gaussian[numdofs+3][numdofm]; //stiffness matrix evaluated at the gaussian point.
    5997         IssmDouble      Ke_gg_gaussian2[numdofm][numdofs+3]; //stiffness matrix evaluated at the gaussian point.
     6032        int         i,j;
     6033        IssmDouble Jdet;
     6034        IssmDouble viscosity,stokesreconditioning; //viscosity
     6035        IssmDouble epsilon[6]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
     6036        IssmDouble xyz_list[NUMVERTICES][3];
     6037        IssmDouble B[4][numdofs+3];
     6038        IssmDouble Bprime[4][numdofm];
     6039        IssmDouble B2[3][numdofm];
     6040        IssmDouble Bprime2[3][numdofs+3];
     6041        IssmDouble D[4][4]={0.0};            // material matrix, simple scalar matrix.
     6042        IssmDouble D2[3][3]={0.0};            // material matrix, simple scalar matrix.
     6043        IssmDouble D_scalar;
     6044        IssmDouble Ke_gg[numdofs][numdofm]={0.0}; //local element stiffness matrix
     6045        IssmDouble Ke_gg2[numdofm][numdofs]={0.0}; //local element stiffness matrix
     6046        IssmDouble Ke_gg_gaussian[numdofs+3][numdofm]; //stiffness matrix evaluated at the gaussian point.
     6047        IssmDouble Ke_gg_gaussian2[numdofm][numdofs+3]; //stiffness matrix evaluated at the gaussian point.
    59986048        GaussPenta *gauss=NULL;
    59996049        GaussTria  *gauss_tria=NULL;
     
    60296079        gauss=new GaussPenta(5,5);
    60306080        gauss_tria=new GaussTria();
    6031         for (ig=gauss->begin();ig<gauss->end();ig++){
     6081        for(int ig=gauss->begin();ig<gauss->end();ig++){
    60326082
    60336083                gauss->GaussPoint(ig);
     
    60866136
    60876137        /*Intermediaries */
    6088         int        i,j,ig;
     6138        int        i,j;
    60896139        int        analysis_type,approximation;
    6090         IssmDouble     stokesreconditioning;
    6091         IssmDouble     viscosity,alpha2_gauss,Jdet2d;
    6092         IssmDouble        bed_normal[3];
    6093         IssmDouble     epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
    6094         IssmDouble     xyz_list[NUMVERTICES][3];
    6095         IssmDouble        xyz_list_tria[NUMVERTICES2D][3];
    6096         IssmDouble     LMacAyealStokes[8][numdof2dm];
    6097         IssmDouble     LprimeMacAyealStokes[8][numdof2d];
    6098         IssmDouble     DLMacAyealStokes[8][8]={0.0};
    6099         IssmDouble     LStokesMacAyeal[4][numdof2d];
    6100         IssmDouble     LprimeStokesMacAyeal[4][numdof2dm];
    6101         IssmDouble     DLStokesMacAyeal[4][4]={0.0};
    6102         IssmDouble     Ke_drag_gaussian[numdof2dm][numdof2d];
    6103         IssmDouble     Ke_drag_gaussian2[numdof2d][numdof2dm];
     6140        IssmDouble stokesreconditioning;
     6141        IssmDouble viscosity,alpha2_gauss,Jdet2d;
     6142        IssmDouble bed_normal[3];
     6143        IssmDouble epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
     6144        IssmDouble xyz_list[NUMVERTICES][3];
     6145        IssmDouble xyz_list_tria[NUMVERTICES2D][3];
     6146        IssmDouble LMacAyealStokes[8][numdof2dm];
     6147        IssmDouble LprimeMacAyealStokes[8][numdof2d];
     6148        IssmDouble DLMacAyealStokes[8][8]={0.0};
     6149        IssmDouble LStokesMacAyeal[4][numdof2d];
     6150        IssmDouble LprimeStokesMacAyeal[4][numdof2dm];
     6151        IssmDouble DLStokesMacAyeal[4][4]={0.0};
     6152        IssmDouble Ke_drag_gaussian[numdof2dm][numdof2d];
     6153        IssmDouble Ke_drag_gaussian2[numdof2d][numdof2dm];
    61046154        Friction*  friction=NULL;
    61056155        GaussPenta *gauss=NULL;
     
    61376187        /* Start  looping on the number of gaussian points: */
    61386188        gauss=new GaussPenta(0,1,2,2);
    6139         for (ig=gauss->begin();ig<gauss->end();ig++){
     6189        for(int ig=gauss->begin();ig<gauss->end();ig++){
    61406190
    61416191                gauss->GaussPoint(ig);
     
    61666216                DLStokesMacAyeal[2][2]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[0]*bed_normal[2];
    61676217                DLStokesMacAyeal[3][3]=-alpha2_gauss*gauss->weight*Jdet2d*bed_normal[1]*bed_normal[2];
    6168                
     6218
    61696219                TripleMultiply( &LMacAyealStokes[0][0],8,numdof2dm,1,
    61706220                                        &DLMacAyealStokes[0][0],8,8,0,
     
    63876437
    63886438        /*Intermediaries */
    6389         int         i,j,ig,approximation;
     6439        int         i,j,approximation;
    63906440        IssmDouble  Jdet;
    63916441        IssmDouble  viscosity , oldviscosity, newviscosity, viscosity_overshoot;
     
    64236473        gauss=new GaussPenta(5,5);
    64246474        gauss_tria=new GaussTria();
    6425         for (ig=gauss->begin();ig<gauss->end();ig++){
     6475        for(int ig=gauss->begin();ig<gauss->end();ig++){
    64266476
    64276477                gauss->GaussPoint(ig);
     
    66386688
    66396689        /*Intermediaries */
    6640         int        i,j,ig;
     6690        int        i,j;
    66416691        int        approximation;
    6642         IssmDouble     xyz_list[NUMVERTICES][3];
    6643         IssmDouble     Jdet;
    6644         IssmDouble     viscosity,oldviscosity,newviscosity,viscosity_overshoot; //viscosity
    6645         IssmDouble     epsilon[5],oldepsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
    6646         IssmDouble     D_scalar;
    6647         IssmDouble     D[5][5]={0.0};            // material matrix, simple scalar matrix.
    6648         IssmDouble     B[5][numdof];
    6649         IssmDouble     Bprime[5][numdof];
     6692        IssmDouble xyz_list[NUMVERTICES][3];
     6693        IssmDouble Jdet;
     6694        IssmDouble viscosity,oldviscosity,newviscosity,viscosity_overshoot; //viscosity
     6695        IssmDouble epsilon[5],oldepsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
     6696        IssmDouble D_scalar;
     6697        IssmDouble D[5][5]={0.0};            // material matrix, simple scalar matrix.
     6698        IssmDouble B[5][numdof];
     6699        IssmDouble Bprime[5][numdof];
    66506700        Tria*      tria=NULL;
    66516701        GaussPenta *gauss=NULL;
     
    66656715        /* Start  looping on the number of gaussian points: */
    66666716        gauss=new GaussPenta(5,5);
    6667         for (ig=gauss->begin();ig<gauss->end();ig++){
     6717        for(int ig=gauss->begin();ig<gauss->end();ig++){
    66686718
    66696719                gauss->GaussPoint(ig);
     
    67016751        /*Constants*/
    67026752        const int numdof   = NDOF2*NUMVERTICES;
    6703        
     6753
    67046754        /*Intermediaries */
    6705         int       i,j,ig;
     6755        int       i,j;
    67066756        int       analysis_type;
    6707         IssmDouble    xyz_list[NUMVERTICES][3];
    6708         IssmDouble    xyz_list_tria[NUMVERTICES2D][3]={0.0};
    6709         IssmDouble    slope_magnitude,alpha2,Jdet;
    6710         IssmDouble    slope[3]={0.0,0.0,0.0};
    6711         IssmDouble    MAXSLOPE=.06; // 6 %
    6712         IssmDouble    MOUNTAINKEXPONENT=10;
    6713         IssmDouble    L[2][numdof];
    6714         IssmDouble    DL[2][2]={{ 0,0 },{0,0}}; //for basal drag
    6715         IssmDouble    DL_scalar;
     6757        IssmDouble xyz_list[NUMVERTICES][3];
     6758        IssmDouble xyz_list_tria[NUMVERTICES2D][3]={0.0};
     6759        IssmDouble slope_magnitude,alpha2,Jdet;
     6760        IssmDouble slope[3]={0.0,0.0,0.0};
     6761        IssmDouble MAXSLOPE=.06; // 6 %
     6762        IssmDouble MOUNTAINKEXPONENT=10;
     6763        IssmDouble L[2][numdof];
     6764        IssmDouble DL[2][2]={{ 0,0 },{0,0}}; //for basal drag
     6765        IssmDouble DL_scalar;
    67166766        Friction  *friction = NULL;
    67176767        GaussPenta *gauss=NULL;
     
    67366786        /* Start  looping on the number of gaussian points: */
    67376787        gauss=new GaussPenta(0,1,2,2);
    6738         for (ig=gauss->begin();ig<gauss->end();ig++){
     6788        for(int ig=gauss->begin();ig<gauss->end();ig++){
    67396789
    67406790                gauss->GaussPoint(ig);
     
    67526802                        alpha2=pow((IssmDouble)10,MOUNTAINKEXPONENT);
    67536803                }
    6754                
     6804
    67556805                DL_scalar=alpha2*gauss->weight*Jdet;
    67566806                for (i=0;i<2;i++) DL[i][i]=DL_scalar;
    6757                
     6807
    67586808                TripleMultiply( &L[0][0],2,numdof,1,
    67596809                                        &DL[0][0],2,2,0,
     
    68056855
    68066856        /*Intermediaries */
    6807         int        i,j,ig,approximation;
    6808         IssmDouble     Jdet,viscosity,stokesreconditioning;
    6809         IssmDouble     xyz_list[NUMVERTICES][3];
    6810         IssmDouble     epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
    6811         IssmDouble     B[8][27];
    6812         IssmDouble     B_prime[8][27];
    6813         IssmDouble     D_scalar;
    6814         IssmDouble     D[8][8]={0.0};
    6815         IssmDouble     Ke_temp[27][27]={0.0}; //for the six nodes and the bubble
     6857        int        i,approximation;
     6858        IssmDouble Jdet,viscosity,stokesreconditioning;
     6859        IssmDouble xyz_list[NUMVERTICES][3];
     6860        IssmDouble epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
     6861        IssmDouble B[8][27];
     6862        IssmDouble B_prime[8][27];
     6863        IssmDouble D_scalar;
     6864        IssmDouble D[8][8]={0.0};
     6865        IssmDouble Ke_temp[27][27]={0.0}; //for the six nodes and the bubble
    68166866        GaussPenta *gauss=NULL;
    68176867
     
    68306880        /* Start  looping on the number of gaussian points: */
    68316881        gauss=new GaussPenta(5,5);
    6832         for (ig=gauss->begin();ig<gauss->end();ig++){
     6882        for(int ig=gauss->begin();ig<gauss->end();ig++){
    68336883
    68346884                gauss->GaussPoint(ig);
     
    68706920
    68716921        /*Intermediaries */
    6872         int        i,j,ig;
     6922        int        i,j;
    68736923        int        analysis_type,approximation;
    6874         IssmDouble     alpha2,Jdet2d;
    6875         IssmDouble     stokesreconditioning,viscosity;
    6876         IssmDouble     epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
    6877         IssmDouble     xyz_list[NUMVERTICES][3];
    6878         IssmDouble        xyz_list_tria[NUMVERTICES2D][3];
    6879         IssmDouble     LStokes[2][numdof2d];
    6880         IssmDouble     DLStokes[2][2]={0.0};
    6881         IssmDouble     Ke_drag_gaussian[numdof2d][numdof2d];
     6924        IssmDouble alpha2,Jdet2d;
     6925        IssmDouble stokesreconditioning,viscosity;
     6926        IssmDouble epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
     6927        IssmDouble xyz_list[NUMVERTICES][3];
     6928        IssmDouble xyz_list_tria[NUMVERTICES2D][3];
     6929        IssmDouble LStokes[2][numdof2d];
     6930        IssmDouble DLStokes[2][2]={0.0};
     6931        IssmDouble Ke_drag_gaussian[numdof2d][numdof2d];
    68826932        Friction*  friction=NULL;
    68836933        GaussPenta *gauss=NULL;
     
    69026952        /* Start  looping on the number of gaussian points: */
    69036953        gauss=new GaussPenta(0,1,2,2);
    6904         for (ig=gauss->begin();ig<gauss->end();ig++){
     6954        for(int ig=gauss->begin();ig<gauss->end();ig++){
    69056955
    69066956                gauss->GaussPoint(ig);
     
    69276977        /*DO NOT Transform Coordinate System: this stiffness matrix is already expressed in tangential coordinates*/
    69286978        //TransformStiffnessMatrixCoord(Ke,nodes,NUMVERTICES,XYZPEnum);
    6929        
     6979
    69306980        /*Clean up and return*/
    69316981        delete gauss;
     
    69366986/*FUNCTION Penta::CreateKMatrixDiagnosticVert {{{*/
    69376987ElementMatrix* Penta::CreateKMatrixDiagnosticVert(void){
    6938        
     6988
    69396989        /*compute all stiffness matrices for this element*/
    69406990        ElementMatrix* Ke1=CreateKMatrixDiagnosticVertVolume();
     
    69567006
    69577007        /*Intermediaries */
    6958         int         i,j,ig;
    6959         IssmDouble      Jdet;
    6960         IssmDouble      xyz_list[NUMVERTICES][3];
    6961         IssmDouble      B[NDOF1][NUMVERTICES];
    6962         IssmDouble      Bprime[NDOF1][NUMVERTICES];
    6963         IssmDouble      DL_scalar;
     7008        IssmDouble  Jdet;
     7009        IssmDouble  xyz_list[NUMVERTICES][3];
     7010        IssmDouble  B[NDOF1][NUMVERTICES];
     7011        IssmDouble  Bprime[NDOF1][NUMVERTICES];
     7012        IssmDouble  DL_scalar;
    69647013        GaussPenta  *gauss=NULL;
    69657014
     
    69727021        /* Start  looping on the number of gaussian points: */
    69737022        gauss=new GaussPenta(2,2);
    6974         for (ig=gauss->begin();ig<gauss->end();ig++){
     7023        for(int ig=gauss->begin();ig<gauss->end();ig++){
    69757024
    69767025                gauss->GaussPoint(ig);
     
    70027051
    70037052        /*Intermediaries */
    7004         int       i,j,ig;
    7005         IssmDouble    xyz_list[NUMVERTICES][3];
    7006         IssmDouble    xyz_list_tria[NUMVERTICES2D][3];
    7007         IssmDouble    surface_normal[3];
    7008         IssmDouble    Jdet2d,DL_scalar;
    7009         IssmDouble    basis[NUMVERTICES];
     7053        int       i,j;
     7054        IssmDouble xyz_list[NUMVERTICES][3];
     7055        IssmDouble xyz_list_tria[NUMVERTICES2D][3];
     7056        IssmDouble surface_normal[3];
     7057        IssmDouble Jdet2d,DL_scalar;
     7058        IssmDouble basis[NUMVERTICES];
    70107059        GaussPenta *gauss=NULL;
    70117060
     
    70207069        /* Start  looping on the number of gaussian points: */
    70217070        gauss=new GaussPenta(3,4,5,2);
    7022         for (ig=gauss->begin();ig<gauss->end();ig++){
     7071        for(int ig=gauss->begin();ig<gauss->end();ig++){
    70237072
    70247073                gauss->GaussPoint(ig);
     
    70617110
    70627111        /*Intermediaries */
    7063         int         i,j,ig;
     7112        int         i,j;
    70647113        int         approximation;
    7065         IssmDouble      viscosity,Jdet;
    7066         IssmDouble      stokesreconditioning;
    7067         IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
    7068         IssmDouble      dw[3];
    7069         IssmDouble      xyz_list[NUMVERTICES][3];
    7070         IssmDouble      basis[6]; //for the six nodes of the penta
    7071         IssmDouble      dbasis[3][6]; //for the six nodes of the penta
     7114        IssmDouble  viscosity,Jdet;
     7115        IssmDouble  stokesreconditioning;
     7116        IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
     7117        IssmDouble  dw[3];
     7118        IssmDouble  xyz_list[NUMVERTICES][3];
     7119        IssmDouble  basis[6]; //for the six nodes of the penta
     7120        IssmDouble  dbasis[3][6]; //for the six nodes of the penta
    70727121        GaussPenta *gauss=NULL;
    70737122
     
    70877136        /* Start  looping on the number of gaussian points: */
    70887137        gauss=new GaussPenta(5,5);
    7089         for (ig=gauss->begin();ig<gauss->end();ig++){
     7138        for(int ig=gauss->begin();ig<gauss->end();ig++){
    70907139
    70917140                gauss->GaussPoint(ig);
     
    71237172
    71247173        /*Intermediaries*/
    7125         int         i,j,ig;
     7174        int         i,j;
    71267175        int         approximation,analysis_type;
    7127         IssmDouble      Jdet,Jdet2d;
    7128         IssmDouble      stokesreconditioning;
    7129         IssmDouble         bed_normal[3];
    7130         IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
    7131         IssmDouble      viscosity, w, alpha2_gauss;
    7132         IssmDouble      dw[3];
    7133         IssmDouble         xyz_list_tria[NUMVERTICES2D][3];
    7134         IssmDouble      xyz_list[NUMVERTICES][3];
    7135         IssmDouble      basis[6]; //for the six nodes of the penta
     7176        IssmDouble  Jdet,Jdet2d;
     7177        IssmDouble  stokesreconditioning;
     7178        IssmDouble      bed_normal[3];
     7179        IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
     7180        IssmDouble  viscosity, w, alpha2_gauss;
     7181        IssmDouble  dw[3];
     7182        IssmDouble      xyz_list_tria[NUMVERTICES2D][3];
     7183        IssmDouble  xyz_list[NUMVERTICES][3];
     7184        IssmDouble  basis[6]; //for the six nodes of the penta
    71367185        Tria*       tria=NULL;
    71377186        Friction*   friction=NULL;
     
    71607209        /* Start looping on the number of gauss 2d (nodes on the bedrock) */
    71617210        gauss=new GaussPenta(0,1,2,2);
    7162         for(ig=gauss->begin();ig<gauss->end();ig++){
     7211        for(int ig=gauss->begin();ig<gauss->end();ig++){
    71637212
    71647213                gauss->GaussPoint(ig);
     
    72127261
    72137262        /*Intermediaries */
    7214         int         i,j,ig;
     7263        int         i;
    72157264        int         approximation;
    7216         IssmDouble      viscosity,Jdet;
    7217         IssmDouble      stokesreconditioning;
    7218         IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
    7219         IssmDouble      dw[3];
    7220         IssmDouble      xyz_list[NUMVERTICES][3];
    7221         IssmDouble      basis[6]; //for the six nodes of the penta
    7222         IssmDouble      dbasis[3][6]; //for the six nodes of the penta
     7265        IssmDouble  viscosity,Jdet;
     7266        IssmDouble  stokesreconditioning;
     7267        IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
     7268        IssmDouble  dw[3];
     7269        IssmDouble  xyz_list[NUMVERTICES][3];
     7270        IssmDouble  basis[6]; //for the six nodes of the penta
     7271        IssmDouble  dbasis[3][6]; //for the six nodes of the penta
    72237272        GaussPenta *gauss=NULL;
    72247273
     
    72387287        /* Start  looping on the number of gaussian points: */
    72397288        gauss=new GaussPenta(5,5);
    7240         for (ig=gauss->begin();ig<gauss->end();ig++){
     7289        for(int ig=gauss->begin();ig<gauss->end();ig++){
    72417290
    72427291                gauss->GaussPoint(ig);
     
    72747323
    72757324        /*Intermediaries*/
    7276         int         i,j,ig;
     7325        int         i,j;
    72777326        int         approximation,analysis_type;
    7278         IssmDouble      Jdet,Jdet2d;
    7279         IssmDouble      stokesreconditioning;
    7280         IssmDouble         bed_normal[3];
    7281         IssmDouble      epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
    7282         IssmDouble      viscosity, w, alpha2_gauss;
    7283         IssmDouble      dw[3];
    7284         IssmDouble         xyz_list_tria[NUMVERTICES2D][3];
    7285         IssmDouble      xyz_list[NUMVERTICES][3];
    7286         IssmDouble      basis[6]; //for the six nodes of the penta
     7327        IssmDouble  Jdet,Jdet2d;
     7328        IssmDouble  stokesreconditioning;
     7329        IssmDouble      bed_normal[3];
     7330        IssmDouble  epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
     7331        IssmDouble  viscosity, w, alpha2_gauss;
     7332        IssmDouble  dw[3];
     7333        IssmDouble      xyz_list_tria[NUMVERTICES2D][3];
     7334        IssmDouble  xyz_list[NUMVERTICES][3];
     7335        IssmDouble  basis[6]; //for the six nodes of the penta
    72877336        Tria*       tria=NULL;
    72887337        Friction*   friction=NULL;
     
    73117360        /* Start looping on the number of gauss 2d (nodes on the bedrock) */
    73127361        gauss=new GaussPenta(0,1,2,2);
    7313         for(ig=gauss->begin();ig<gauss->end();ig++){
     7362        for(int ig=gauss->begin();ig<gauss->end();ig++){
    73147363
    73157364                gauss->GaussPoint(ig);
     
    74217470ElementVector* Penta::CreatePVectorDiagnosticHutter(void){
    74227471
    7423         /*Constants*/
    7424         const int numdofs=NDOF2*NUMVERTICES;
    7425 
    74267472        /*Intermediaries*/
    7427         int          i,j,k,ig;
     7473        int          i,j;
    74287474        int          node0,node1;
    74297475        int          connectivity[2];
    7430         IssmDouble       Jdet;
    7431         IssmDouble       xyz_list[NUMVERTICES][3];
    7432         IssmDouble       xyz_list_segment[2][3];
    7433         IssmDouble       z_list[NUMVERTICES];
    7434         IssmDouble       z_segment[2],slope[2];
    7435         IssmDouble       slope2,constant_part;
    7436         IssmDouble       rho_ice,gravity,n,B;
    7437         IssmDouble       ub,vb,z_g,surface,thickness;
     7476        IssmDouble   Jdet;
     7477        IssmDouble   xyz_list[NUMVERTICES][3];
     7478        IssmDouble   xyz_list_segment[2][3];
     7479        IssmDouble   z_list[NUMVERTICES];
     7480        IssmDouble   slope[2];
     7481        IssmDouble   slope2,constant_part;
     7482        IssmDouble   rho_ice,gravity,n,B;
     7483        IssmDouble   ub,vb,z_g,surface,thickness;
    74387484        GaussPenta*  gauss=NULL;
    74397485
     
    74687514                /*Loop on the Gauss points: */
    74697515                gauss=new GaussPenta(node0,node1,3);
    7470                 for(ig=gauss->begin();ig<gauss->end();ig++){
     7516                for(int ig=gauss->begin();ig<gauss->end();ig++){
    74717517                        gauss->GaussPoint(ig);
    74727518
     
    75417587
    75427588        /*Intermediaries*/
    7543         int         i,j,ig;
    7544         IssmDouble      Jdet;
    7545         IssmDouble      slope[3]; //do not put 2! this goes into GetInputDerivativeValue, which addresses slope[3] also!
    7546         IssmDouble      driving_stress_baseline,thickness;
    7547         IssmDouble      xyz_list[NUMVERTICES][3];
    7548         IssmDouble      basis[6];
     7589        int         i,j;
     7590        IssmDouble  Jdet;
     7591        IssmDouble  slope[3]; //do not put 2! this goes into GetInputDerivativeValue, which addresses slope[3] also!
     7592        IssmDouble  driving_stress_baseline,thickness;
     7593        IssmDouble  xyz_list[NUMVERTICES][3];
     7594        IssmDouble  basis[6];
    75497595        GaussPenta  *gauss=NULL;
    75507596
     
    75597605        /* Start  looping on the number of gaussian points: */
    75607606        gauss=new GaussPenta(2,3);
    7561         for (ig=gauss->begin();ig<gauss->end();ig++){
     7607        for(int ig=gauss->begin();ig<gauss->end();ig++){
    75627608
    75637609                gauss->GaussPoint(ig);
     
    76037649
    76047650        /*Intermediaries*/
    7605         int        i,j,ig;
     7651        int        i,j;
    76067652        int        approximation;
    7607         IssmDouble     Jdet,viscosity;
    7608         IssmDouble     gravity,rho_ice,stokesreconditioning;
    7609         IssmDouble     xyz_list[NUMVERTICES][3];
    7610         IssmDouble     epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
    7611         IssmDouble     l1l7[7]; //for the six nodes and the bubble
    7612         IssmDouble     B[8][numdofbubble];
    7613         IssmDouble     B_prime[8][numdofbubble];
    7614         IssmDouble     B_prime_bubble[8][3];
    7615         IssmDouble     D[8][8]={0.0};
    7616         IssmDouble     D_scalar;
    7617         IssmDouble     Pe_gaussian[numdofbubble]={0.0}; //for the six nodes and the bubble
    7618         IssmDouble     Ke_temp[numdofbubble][3]={0.0}; //for the six nodes and the bubble
    7619         IssmDouble     Ke_gaussian[numdofbubble][3];
     7653        IssmDouble Jdet,viscosity;
     7654        IssmDouble gravity,rho_ice,stokesreconditioning;
     7655        IssmDouble xyz_list[NUMVERTICES][3];
     7656        IssmDouble epsilon[6]; /* epsilon=[exx,eyy,ezz,exy,exz,eyz];*/
     7657        IssmDouble l1l7[7]; //for the six nodes and the bubble
     7658        IssmDouble B[8][numdofbubble];
     7659        IssmDouble B_prime[8][numdofbubble];
     7660        IssmDouble B_prime_bubble[8][3];
     7661        IssmDouble D[8][8]={0.0};
     7662        IssmDouble D_scalar;
     7663        IssmDouble Pe_gaussian[numdofbubble]={0.0}; //for the six nodes and the bubble
     7664        IssmDouble Ke_temp[numdofbubble][3]={0.0}; //for the six nodes and the bubble
    76207665        GaussPenta *gauss=NULL;
    76217666
     
    76367681        /* Start  looping on the number of gaussian points: */
    76377682        gauss=new GaussPenta(5,5);
    7638         for (ig=gauss->begin();ig<gauss->end();ig++){
     7683        for(int ig=gauss->begin();ig<gauss->end();ig++){
    76397684
    76407685                gauss->GaussPoint(ig);
     
    76807725
    76817726        /*Intermediaries*/
    7682         int         i,j,ig;
     7727        int         i,j;
    76837728        int         approximation,shelf_dampening;
    7684         IssmDouble      gravity,rho_water,bed,water_pressure;
    7685         IssmDouble      damper,normal_vel,vx,vy,vz,dt;
    7686         IssmDouble              xyz_list_tria[NUMVERTICES2D][3];
    7687         IssmDouble      xyz_list[NUMVERTICES][3];
    7688         IssmDouble              bed_normal[3];
    7689         IssmDouble      dz[3];
    7690         IssmDouble      basis[6]; //for the six nodes of the penta
    7691         IssmDouble      Jdet2d;
     7729        IssmDouble  gravity,rho_water,bed,water_pressure;
     7730        IssmDouble  damper,normal_vel,vx,vy,vz,dt;
     7731        IssmDouble      xyz_list_tria[NUMVERTICES2D][3];
     7732        IssmDouble  xyz_list[NUMVERTICES][3];
     7733        IssmDouble      bed_normal[3];
     7734        IssmDouble  dz[3];
     7735        IssmDouble  basis[6]; //for the six nodes of the penta
     7736        IssmDouble  Jdet2d;
    76927737        GaussPenta  *gauss=NULL;
    76937738
     
    77127757        /* Start looping on the number of gauss 2d (nodes on the bedrock) */
    77137758        gauss=new GaussPenta(0,1,2,2);
    7714         for(ig=gauss->begin();ig<gauss->end();ig++){
     7759        for(int ig=gauss->begin();ig<gauss->end();ig++){
    77157760
    77167761                gauss->GaussPoint(ig);
     
    77657810
    77667811        /*Intermediaries*/
    7767         int        i,ig;
    77687812        int        approximation;
    77697813        IssmDouble     Jdet;
     
    77897833        /* Start  looping on the number of gaussian points: */
    77907834        gauss=new GaussPenta(2,2);
    7791         for (ig=gauss->begin();ig<gauss->end();ig++){
     7835        for(int ig=gauss->begin();ig<gauss->end();ig++){
    77927836
    77937837                gauss->GaussPoint(ig);
     
    78067850                dvdy=dv[1];
    78077851
    7808                 for (i=0;i<numdof;i++) pe->values[i] += (dudx+dvdy+dwdz)*Jdet*gauss->weight*basis[i];
     7852                for(int i=0;i<numdof;i++) pe->values[i] += (dudx+dvdy+dwdz)*Jdet*gauss->weight*basis[i];
    78097853        }
    78107854
     
    78177861ElementVector* Penta::CreatePVectorDiagnosticVertBase(void){
    78187862
    7819 
    78207863        /*Constants*/
    78217864        const int    numdof=NDOF1*NUMVERTICES;
    78227865
    78237866        /*Intermediaries */
    7824         int        i,j,ig;
     7867        int        i,j;
    78257868        int        approximation;
    7826         IssmDouble     xyz_list[NUMVERTICES][3];
    7827         IssmDouble     xyz_list_tria[NUMVERTICES2D][3];
    7828         IssmDouble     Jdet2d;
    7829         IssmDouble     vx,vy,vz,dbdx,dbdy,basalmeltingvalue;
    7830         IssmDouble     slope[3];
    7831         IssmDouble     basis[NUMVERTICES];
     7869        IssmDouble xyz_list[NUMVERTICES][3];
     7870        IssmDouble xyz_list_tria[NUMVERTICES2D][3];
     7871        IssmDouble Jdet2d;
     7872        IssmDouble vx,vy,vz,dbdx,dbdy,basalmeltingvalue;
     7873        IssmDouble slope[3];
     7874        IssmDouble basis[NUMVERTICES];
    78327875        GaussPenta* gauss=NULL;
    78337876
     
    78527895        /* Start  looping on the number of gaussian points: */
    78537896        gauss=new GaussPenta(0,1,2,2);
    7854         for(ig=gauss->begin();ig<gauss->end();ig++){
     7897        for(int ig=gauss->begin();ig<gauss->end();ig++){
    78557898
    78567899                gauss->GaussPoint(ig);
     
    79407983
    79417984        /*Intermediaries */
    7942         int        i,j,ig;
    7943         IssmDouble     xyz_list[NUMVERTICES][3];
    7944         IssmDouble     Jdet;
    7945         IssmDouble     eps1dotdphii,eps1dotdphij;
    7946         IssmDouble     eps2dotdphii,eps2dotdphij;
    7947         IssmDouble     mu_prime;
    7948         IssmDouble     epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
    7949         IssmDouble     eps1[3],eps2[3];
    7950         IssmDouble     phi[NUMVERTICES];
    7951         IssmDouble     dphi[3][NUMVERTICES];
     7985        int        i,j;
     7986        IssmDouble xyz_list[NUMVERTICES][3];
     7987        IssmDouble Jdet;
     7988        IssmDouble eps1dotdphii,eps1dotdphij;
     7989        IssmDouble eps2dotdphii,eps2dotdphij;
     7990        IssmDouble mu_prime;
     7991        IssmDouble epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
     7992        IssmDouble eps1[3],eps2[3];
     7993        IssmDouble dphi[3][NUMVERTICES];
    79527994        GaussPenta *gauss=NULL;
    79537995
     
    79628004        /* Start  looping on the number of gaussian points: */
    79638005        gauss=new GaussPenta(5,5);
    7964         for (ig=gauss->begin();ig<gauss->end();ig++){
     8006        for(int ig=gauss->begin();ig<gauss->end();ig++){
    79658007
    79668008                gauss->GaussPoint(ig);
     
    80058047
    80068048        /*Intermediaries */
    8007         int        i,j,ig;
    8008         IssmDouble     xyz_list[NUMVERTICES][3];
    8009         IssmDouble     Jdet;
    8010         IssmDouble     eps1dotdphii,eps1dotdphij;
    8011         IssmDouble     eps2dotdphii,eps2dotdphij;
    8012         IssmDouble     eps3dotdphii,eps3dotdphij;
    8013         IssmDouble     mu_prime;
    8014         IssmDouble     epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
    8015         IssmDouble     eps1[3],eps2[3],eps3[3];
    8016         IssmDouble     phi[NUMVERTICES];
    8017         IssmDouble     dphi[3][NUMVERTICES];
     8049        int        i,j;
     8050        IssmDouble xyz_list[NUMVERTICES][3];
     8051        IssmDouble Jdet;
     8052        IssmDouble eps1dotdphii,eps1dotdphij;
     8053        IssmDouble eps2dotdphii,eps2dotdphij;
     8054        IssmDouble eps3dotdphii,eps3dotdphij;
     8055        IssmDouble mu_prime;
     8056        IssmDouble epsilon[5]; /* epsilon=[exx,eyy,exy,exz,eyz];*/
     8057        IssmDouble eps1[3],eps2[3],eps3[3];
     8058        IssmDouble dphi[3][NUMVERTICES];
    80188059        GaussPenta *gauss=NULL;
    80198060
     
    80298070        /* Start  looping on the number of gaussian points: */
    80308071        gauss=new GaussPenta(5,5);
    8031         for (ig=gauss->begin();ig<gauss->end();ig++){
     8072        for(int ig=gauss->begin();ig<gauss->end();ig++){
    80328073
    80338074                gauss->GaussPoint(ig);
     
    84168457                penta=penta->GetUpperElement(); _assert_(penta->Id()!=this->id);
    84178458        }
    8418        
     8459
    84198460        /*Free ressources:*/
    84208461        xDelete<int>(doflist);
     
    86888729/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticPattyn {{{*/
    86898730void  Penta::InputUpdateFromSolutionDiagnosticPattyn(IssmDouble* solution){
    8690        
     8731
    86918732        const int    numdof=NDOF2*NUMVERTICES;
    86928733
     
    88568897/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticHutter {{{*/
    88578898void  Penta::InputUpdateFromSolutionDiagnosticHutter(IssmDouble* solution){
    8858        
     8899
    88598900        const int    numdof=NDOF2*NUMVERTICES;
    88608901
     
    89218962
    89228963        const int numdof=NDOF1*NUMVERTICES;
    8923        
     8964
    89248965        int      i;
    89258966        int      approximation;
     
    89388979        int*     doflist      = NULL;
    89398980
    8940 
    89418981        /*Get the approximation and do nothing if the element in Stokes or None*/
    89428982        inputs->GetInputValue(&approximation,ApproximationEnum);
     
    90239063/*FUNCTION Penta::InputUpdateFromSolutionDiagnosticStokes {{{*/
    90249064void  Penta::InputUpdateFromSolutionDiagnosticStokes(IssmDouble* solution){
    9025        
     9065
    90269066        const int numdof=NDOF4*NUMVERTICES;
    90279067
     
    90639103        for(i=0;i<NUMVERTICES;i++) pressure[i]=pressure[i]*stokesreconditioning;
    90649104        for(i=0;i<NUMVERTICES;i++) vel[i]=pow( pow(vx[i],2.0) + pow(vy[i],2.0) + pow(vz[i],2.0) , 0.5);
    9065        
     9105
    90669106        /*Now, we have to move the previous inputs  to old
    90679107         * status, otherwise, we'll wipe them off: */
     
    91339173/*}}}*/
    91349174#endif
    9135 
  • issm/trunk/src/c/classes/objects/Elements/Penta.h

    r13395 r13975  
    3434                int          sid;
    3535
    36                 Node       **nodes;        // 6 nodes
    37                 Material    *material;       // 1 material ice
    38                 Matpar      *matpar;       // 1 material parameter
    39                 Penta      **verticalneighbors;   // 2 neighbors: first one under, second one above
     36                Node       **nodes;                       // 6 nodes
     37                Material    *material;                    // 1 material ice
     38                Matpar      *matpar;                      // 1 material parameter
     39                Penta      **verticalneighbors;           // 2 neighbors: first one under, second one above
    4040                int          horizontalneighborsids[3];
    4141
    42                 Parameters  *parameters;   //pointer to solution parameters
     42                Parameters  *parameters;                  //pointer to solution parameters
    4343                Inputs      *inputs;
    44                 Results      *results;
     44                Results     *results;
    4545
    4646                /*Penta constructors and destructor: {{{*/
     
    5050                /*}}}*/
    5151                /*Object virtual functions definitions: {{{*/
    52                 Object*   copy();
    53                 void      DeepEcho();
    54                 void      Echo();
    55                 int               ObjectEnum();
    56                 int               Id();
    57                 int               MyRank();
     52                Object *copy();
     53                void    DeepEcho();
     54                void    Echo();
     55                int     ObjectEnum();
     56                int     Id();
    5857                /*}}}*/
    5958                /*Update virtual functions definitions: {{{*/
     
    8180                void   Configure(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters);
    8281                void   SetCurrentConfiguration(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters);
     82                void   SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
    8383                void   CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,Vector<IssmDouble>* df);
    8484                void   CreatePVector(Vector<IssmDouble>* pf);
     
    8787                void   DeleteResults(void);
    8888                int    GetNodeIndex(Node* node);
     89                void   GetNodesSidList(int* sidlist);
     90                int    GetNumberOfNodes(void);
    8991                void   GetSolutionFromInputs(Vector<IssmDouble>* solution);
    9092                IssmDouble GetZcoord(GaussPenta* gauss);
    9193                void   GetVectorFromInputs(Vector<IssmDouble>* vector,int name_enum);
    9294                void   GetVectorFromResults(Vector<IssmDouble>* vector,int offset,int name_enum,int interp);
    93                
     95
    9496                int    Sid();
    9597                void   InputArtificialNoise(int enum_type,IssmDouble min, IssmDouble max);
     
    100102                void   InputDuplicate(int original_enum,int new_enum);
    101103                void   InputScale(int enum_type,IssmDouble scale_factor);
    102                
     104
    103105                void   InputToResult(int enum_type,int step,IssmDouble time);
    104106                void   MigrateGroundingLine(IssmDouble* old_floating_ice,IssmDouble* sheet_ungrounding);
     
    174176                ElementVector* CreatePVectorSlope(void);
    175177                void      GetDofList(int** pdoflist,int approximation_enum,int setenum);
    176                 void      GetDofList1(int* doflist);
    177                 void    GetSidList(int* sidlist);
     178                void      GetVertexPidList(int* doflist);
     179                void    GetVertexSidList(int* sidlist);
    178180                void    GetConnectivityList(int* connectivity);
    179181                int     GetElementType(void);
  • issm/trunk/src/c/classes/objects/Elements/PentaHook.cpp

    r13395 r13975  
    4949        /*intermediary: */
    5050        int matpar_id;
    51        
     51
    5252        /*retrieve parameters: */
    5353        iomodel->Constant(&matpar_id,MeshNumberofelementsEnum); matpar_id++;
     
    7070void PentaHook::SetHookNodes(int* node_ids,int analysis_counter){
    7171        this->hnodes[analysis_counter]= new Hook(node_ids,6);
    72 
    7372}
    7473/*}}}*/
  • issm/trunk/src/c/classes/objects/Elements/PentaHook.h

    r13395 r13975  
    1313
    1414        public:
    15                 int   numanalyses; //number of analysis types
    16                 Hook** hnodes; // 6 nodes for each analysis type
    17                 Hook*  hmaterial; // 1 ice material
    18                 Hook*  hmatpar; // 1 material parameter
    19                 Hook*  hneighbors; // 2 elements, first down, second up
     15                int    numanalyses;  //number of analysis types
     16                Hook **hnodes;        // 6 nodes for each analysis type
     17                Hook  *hmaterial;    // 1 ice material
     18                Hook  *hmatpar;      // 1 material parameter
     19                Hook  *hneighbors;    // 2 elements, first down, second up
    2020
    21                 /*FUNCTION constructors, destructors {{{*/
     21                /*constructors, destructors*/
    2222                PentaHook();
    2323                PentaHook(int in_numanalyses,int material_id, IoModel* iomodel);
    2424                ~PentaHook();
     25
    2526                void SetHookNodes(int* node_ids,int analysis_counter);
    2627                void SpawnTriaHook(TriaHook* triahook,int* indices);
    2728                void InitHookNeighbors(int* element_ids);
    28                 /*}}}*/
    2929};
    3030
    31 
    3231#endif //ifndef _PENTAHOOK_H_
    33 
  • issm/trunk/src/c/classes/objects/Elements/PentaRef.cpp

    r13395 r13975  
    699699        IssmDouble l1l2l3[NUMNODESP1_2d];
    700700
    701 
    702701        /*Get l1l2l3 in actual coordinate system: */
    703702        l1l2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
     
    812811        IssmDouble l1l2l3[NUMNODESP1_2d];
    813812
    814 
    815813        /*Get l1l2l3 in actual coordinate system: */
    816814        l1l2l3[0]=gauss->coord1*(1-gauss->coord4)/2.0;
     
    882880void PentaRef::GetJacobian(IssmDouble* J, IssmDouble* xyz_list,GaussPenta* gauss){
    883881
    884         int i,j;
    885 
    886882        /*The Jacobian is constant over the element, discard the gaussian points.
    887883         * J is assumed to have been allocated of size NDOF2xNDOF2.*/
     
    899895        A3=gauss->coord3;
    900896
    901         xi=A2-A1;
    902         eta=SQRT3*A3;
    903         zi=gauss->coord4;
     897        xi  = A2-A1;
     898        eta = SQRT3*A3;
     899        zi  = gauss->coord4;
    904900
    905901        x1=*(xyz_list+3*0+0);
  • issm/trunk/src/c/classes/objects/Elements/PentaRef.h

    r13395 r13975  
    44 */
    55
    6 
    76#ifndef _PENTAREF_H_
    87#define _PENTAREF_H_
    98
    109class PentaRef{
    11        
    1210
    1311        public:
    1412                int* element_type_list; //P1CG, P1DG, MINI, P2...
    1513                int  element_type;
    16                
     14
    1715                PentaRef();
    1816                PentaRef(const int nummodels);
  • issm/trunk/src/c/classes/objects/Elements/Tria.cpp

    r13395 r13975  
    4242        :TriaRef(nummodels)
    4343        ,TriaHook(nummodels,index+1,iomodel){
    44                
    45                 int i;
     44
    4645                /*id: */
    4746                this->id=tria_id;
     
    127126void  Tria::AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part){
    128127
    129         bool      already=false;
    130         int       i,j;
    131         int       partition[NUMVERTICES];
    132         int       offsetsid[NUMVERTICES];
    133         int       offsetdof[NUMVERTICES];
    134         IssmDouble    area;
    135         IssmDouble    mean;
    136         IssmDouble    values[3];
     128        bool       already = false;
     129        int        i,j;
     130        int        partition[NUMVERTICES];
     131        int        offsetsid[NUMVERTICES];
     132        int        offsetdof[NUMVERTICES];
     133        IssmDouble area;
     134        IssmDouble mean;
    137135
    138136        /*First, get the area: */
     
    140138
    141139        /*Figure out the average for this element: */
    142         this->GetSidList(&offsetsid[0]);
    143         this->GetDofList1(&offsetdof[0]);
     140        this->GetVertexSidList(&offsetsid[0]);
     141        this->GetVertexPidList(&offsetdof[0]);
    144142        mean=0;
    145143        for(i=0;i<NUMVERTICES;i++){
     
    164162}
    165163/*}}}*/
     164/*FUNCTION Tria::SetwiseNodeConnectivity{{{*/
     165void Tria::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
     166
     167        /*Output */
     168        int d_nz = 0;
     169        int o_nz = 0;
     170
     171        /*Loop over all nodes*/
     172        for(int i=0;i<3;i++){
     173
     174                if(!flags[this->nodes[i]->Sid()]){
     175
     176                        /*flag current node so that no other element processes it*/
     177                        flags[this->nodes[i]->Sid()]=true;
     178
     179                        /*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
     180                        switch(set2_enum){
     181                                case FsetEnum:
     182                                        if(nodes[i]->indexing.fsize){
     183                                                if(this->nodes[i]->IsClone())
     184                                                 o_nz += 1;
     185                                                else
     186                                                 d_nz += 1;
     187                                        }
     188                                        break;
     189                                case GsetEnum:
     190                                        if(nodes[i]->indexing.gsize){
     191                                                if(this->nodes[i]->IsClone())
     192                                                 o_nz += 1;
     193                                                else
     194                                                 d_nz += 1;
     195                                        }
     196                                        break;
     197                                case SsetEnum:
     198                                        if(nodes[i]->indexing.ssize){
     199                                                if(this->nodes[i]->IsClone())
     200                                                 o_nz += 1;
     201                                                else
     202                                                 d_nz += 1;
     203                                        }
     204                                        break;
     205                                default: _error_("not supported");
     206                        }
     207                }
     208        }
     209
     210        /*Assign output pointers: */
     211        *pd_nz=d_nz;
     212        *po_nz=o_nz;
     213}
     214/*}}}*/
    166215/*FUNCTION Tria::CreateKMatrix {{{*/
    167216void  Tria::CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,Vector<IssmDouble>* df){
     
    175224        _assert_(this->nodes && this->material && this->matpar && this->parameters && this->inputs);
    176225        /*}}}*/
    177        
     226
    178227        /*Skip if water element*/
    179228        if(IsOnWater()) return;
     
    231280
    232281        /*Intermediaries */
    233         int        i,j,ig;
    234282        IssmDouble heatcapacity,latentheat;
    235283        IssmDouble Jdet,D_scalar;
     
    248296        /* Start looping on the number of gauss  (nodes on the bedrock) */
    249297        gauss=new GaussTria(2);
    250         for (ig=gauss->begin();ig<gauss->end();ig++){
     298        for(int ig=gauss->begin();ig<gauss->end();ig++){
    251299
    252300                gauss->GaussPoint(ig);
     
    290338        /*Intermediaries */
    291339        int        stabilization;
    292         int        i,j,ig,dim;
    293         IssmDouble     Jdettria,DL_scalar,dt,h;
    294         IssmDouble     vel,vx,vy,dvxdx,dvydy;
    295         IssmDouble     dvx[2],dvy[2];
    296         IssmDouble     v_gauss[2]={0.0};
    297         IssmDouble     xyz_list[NUMVERTICES][3];
    298         IssmDouble     L[NUMVERTICES];
    299         IssmDouble     B[2][NUMVERTICES];
    300         IssmDouble     Bprime[2][NUMVERTICES];
    301         IssmDouble     K[2][2]                        ={0.0};
    302         IssmDouble     KDL[2][2]                      ={0.0};
    303         IssmDouble     DL[2][2]                        ={0.0};
    304         IssmDouble     DLprime[2][2]                   ={0.0};
    305         GaussTria *gauss=NULL;
     340        int        dim;
     341        IssmDouble Jdettria,DL_scalar,dt,h;
     342        IssmDouble vel,vx,vy,dvxdx,dvydy;
     343        IssmDouble dvx[2],dvy[2];
     344        IssmDouble v_gauss[2]={0.0};
     345        IssmDouble xyz_list[NUMVERTICES][3];
     346        IssmDouble L[NUMVERTICES];
     347        IssmDouble B[2][NUMVERTICES];
     348        IssmDouble Bprime[2][NUMVERTICES];
     349        IssmDouble K[2][2]                        ={0.0};
     350        IssmDouble KDL[2][2]                      ={0.0};
     351        IssmDouble DL[2][2]                        ={0.0};
     352        IssmDouble DLprime[2][2]                   ={0.0};
    306353
    307354        /*Initialize Element matrix*/
     
    326373
    327374        /* Start  looping on the number of gaussian points: */
    328         gauss=new GaussTria(2);
    329         for (ig=gauss->begin();ig<gauss->end();ig++){
     375        GaussTria *gauss=new GaussTria(2);
     376        for(int ig=gauss->begin();ig<gauss->end();ig++){
    330377
    331378                gauss->GaussPoint(ig);
     
    409456
    410457        /*Intermediaries */
    411         int        i,j,ig,dim;
    412         IssmDouble     xyz_list[NUMVERTICES][3];
    413         IssmDouble     Jdettria,dt,vx,vy;
    414         IssmDouble     L[NUMVERTICES];
    415         IssmDouble     B[2][NUMVERTICES];
    416         IssmDouble     Bprime[2][NUMVERTICES];
    417         IssmDouble     DL[2][2]={0.0};
    418         IssmDouble     DLprime[2][2]={0.0};
    419         IssmDouble     DL_scalar;
     458        int        dim;
     459        IssmDouble xyz_list[NUMVERTICES][3];
     460        IssmDouble Jdettria,dt,vx,vy;
     461        IssmDouble L[NUMVERTICES];
     462        IssmDouble B[2][NUMVERTICES];
     463        IssmDouble Bprime[2][NUMVERTICES];
     464        IssmDouble DL[2][2]={0.0};
     465        IssmDouble DLprime[2][2]={0.0};
     466        IssmDouble DL_scalar;
    420467        GaussTria  *gauss=NULL;
    421468
     
    440487        /* Start  looping on the number of gaussian points: */
    441488        gauss=new GaussTria(2);
    442         for (ig=gauss->begin();ig<gauss->end();ig++){
     489        for(int ig=gauss->begin();ig<gauss->end();ig++){
    443490
    444491                gauss->GaussPoint(ig);
     
    499546
    500547                gauss->GaussPoint(ig);
    501                
     548
    502549                GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
    503550                D=gauss->weight*Jdet;
     
    528575        _assert_(this->nodes && this->material && this->matpar && this->parameters && this->inputs);
    529576        /*}}}*/
    530        
     577
    531578        /*Skip if water element*/
    532579        if(IsOnWater()) return;
     
    597644
    598645        /*Intermediaries */
    599         int        i,j,ig;
    600         IssmDouble     Jdettria,dt;
    601         IssmDouble     surface_mass_balance_g,basal_melting_g,basal_melting_correction_g,thickness_g;
    602         IssmDouble     xyz_list[NUMVERTICES][3];
    603         IssmDouble     L[NUMVERTICES];
     646        IssmDouble Jdettria,dt;
     647        IssmDouble surface_mass_balance_g,basal_melting_g,basal_melting_correction_g,thickness_g;
     648        IssmDouble xyz_list[NUMVERTICES][3];
     649        IssmDouble L[NUMVERTICES];
    604650        GaussTria* gauss=NULL;
    605651
     
    618664        /* Start  looping on the number of gaussian points: */
    619665        gauss=new GaussTria(2);
    620         for(ig=gauss->begin();ig<gauss->end();ig++){
     666        for(int ig=gauss->begin();ig<gauss->end();ig++){
    621667
    622668                gauss->GaussPoint(ig);
     
    633679                 basal_melting_correction_g=0.;
    634680
    635                 for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(thickness_g+dt*(surface_mass_balance_g-basal_melting_g-basal_melting_correction_g))*L[i];
     681                for(int i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(thickness_g+dt*(surface_mass_balance_g-basal_melting_g-basal_melting_correction_g))*L[i];
    636682        }
    637683
     
    648694
    649695        /*Intermediaries */
    650         int        i,j,ig;
    651         IssmDouble     Jdettria,dt;
    652         IssmDouble     surface_mass_balance_g,basal_melting_g,thickness_g;
    653         IssmDouble     xyz_list[NUMVERTICES][3];
    654         IssmDouble     L[NUMVERTICES];
     696        IssmDouble Jdettria,dt;
     697        IssmDouble surface_mass_balance_g,basal_melting_g,thickness_g;
     698        IssmDouble xyz_list[NUMVERTICES][3];
     699        IssmDouble L[NUMVERTICES];
    655700        GaussTria* gauss=NULL;
    656701
     
    667712        /* Start  looping on the number of gaussian points: */
    668713        gauss=new GaussTria(2);
    669         for(ig=gauss->begin();ig<gauss->end();ig++){
     714        for(int ig=gauss->begin();ig<gauss->end();ig++){
    670715
    671716                gauss->GaussPoint(ig);
     
    678723                thickness_input->GetInputValue(&thickness_g,gauss);
    679724
    680                 for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(thickness_g+dt*(surface_mass_balance_g-basal_melting_g))*L[i];
     725                for(int i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*(thickness_g+dt*(surface_mass_balance_g-basal_melting_g))*L[i];
    681726        }
    682727
     
    691736        /*Constants*/
    692737        const int    numdof=NDOF1*NUMVERTICES;
    693        
     738
    694739        /*Intermediaries */
    695         int        i,j,ig;
     740        int        i;
    696741        int        analysis_type;
    697         IssmDouble     Jdet;
    698         IssmDouble     xyz_list[NUMVERTICES][3];
    699         IssmDouble     slope[2];
    700         IssmDouble     basis[3];
     742        IssmDouble Jdet;
     743        IssmDouble xyz_list[NUMVERTICES][3];
     744        IssmDouble slope[2];
     745        IssmDouble basis[3];
    701746        GaussTria* gauss=NULL;
    702747
     
    714759                slope_input=inputs->GetInput(BedEnum);     _assert_(slope_input);
    715760        }
    716                
     761
    717762        /* Start  looping on the number of gaussian points: */
    718763        gauss=new GaussTria(2);
    719         for(ig=gauss->begin();ig<gauss->end();ig++){
     764        for(int ig=gauss->begin();ig<gauss->end();ig++){
    720765
    721766                gauss->GaussPoint(ig);
     
    785830void  Tria::ComputeStressTensor(){
    786831
    787         int         iv;
    788832        IssmDouble      xyz_list[NUMVERTICES][3];
    789833        IssmDouble      pressure,viscosity;
     
    820864                sigma_xy[iv]=2*viscosity*epsilon[2];
    821865        }
    822        
     866
    823867        /*Add Stress tensor components into inputs*/
    824868        this->inputs->AddInput(new TriaP1Input(StressTensorxxEnum,&sigma_xx[0]));
     
    835879/*FUNCTION Tria::Configure {{{*/
    836880void  Tria::Configure(Elements* elementsin, Loads* loadsin, DataSet* nodesin, Materials* materialsin, Parameters* parametersin){
    837        
     881
    838882        /*go into parameters and get the analysis_counter: */
    839883        int analysis_counter;
     
    894938        _printLine_("neighboor sids: ");
    895939        _printLine_(" " << horizontalneighborsids[0] << " " << horizontalneighborsids[1] << " " << horizontalneighborsids[2]);
    896        
     940
    897941        return;
    898942}
     
    946990        this->parameters->FindParam(&Delta18oSurfaceLgm,SurfaceforcingsDelta18oSurfaceEnum,(finaltime-(21000*yts)));
    947991        this->parameters->FindParam(&Delta18oSurfaceTime,SurfaceforcingsDelta18oSurfaceEnum,time);
    948        
     992
    949993        /*Compute the temperature and precipitation*/
    950994        for(int iv=0;iv<NUMVERTICES;iv++){
     
    10271071        x2=xyz_list[1][0]; y2=xyz_list[1][1];
    10281072        x3=xyz_list[2][0]; y3=xyz_list[2][1];
    1029  
     1073
    10301074        _assert_(x2*y3 - y2*x3 + x1*y2 - y1*x2 + x3*y1 - y3*x1>0);
    10311075        return (x2*y3 - y2*x3 + x1*y2 - y1*x2 + x3*y1 - y3*x1)/2;
     
    10551099}
    10561100/*}}}*/
    1057 /*FUNCTION Tria::GetDofList1 {{{*/
    1058 void  Tria::GetDofList1(int* doflist){
    1059 
    1060         int i;
    1061         for(i=0;i<3;i++) doflist[i]=nodes[i]->GetDofList1();
    1062 
    1063 }
    1064 /*}}}*/
    10651101/*FUNCTION Tria::GetElementType {{{*/
    10661102int Tria::GetElementType(){
     
    10901126}
    10911127/*}}}*/
     1128/*FUNCTION Tria::GetNodesSidList{{{*/
     1129void Tria::GetNodesSidList(int* sidlist){
     1130
     1131        _assert_(sidlist);
     1132        _assert_(nodes);
     1133
     1134        for(int i=0;i<NUMVERTICES;i++){
     1135                sidlist[i]=nodes[i]->Sid();
     1136        }
     1137}
     1138/*}}}*/
     1139/*FUNCTION Tria::GetNumberOfNodes{{{*/
     1140int Tria::GetNumberOfNodes(void){
     1141
     1142        if(this->nodes==NULL) return 0;
     1143
     1144        switch(this->element_type){
     1145                case P1Enum:
     1146                        return 3;
     1147                case P1DGEnum:
     1148                        return 3;
     1149                default:
     1150                        _error_("Element type "<<EnumToStringx(this->element_type)<<" not supported yet");
     1151        }
     1152}
     1153/*}}}*/
    10921154/*FUNCTION Tria::GetInputListOnVertices(IssmDouble* pvalue,int enumtype) {{{*/
    10931155void Tria::GetInputListOnVertices(IssmDouble* pvalue,int enumtype){
    1094 
    1095         /*Intermediaries*/
    1096         IssmDouble     value[NUMVERTICES];
    1097         GaussTria *gauss              = NULL;
    10981156
    10991157        /*Recover input*/
     
    11051163
    11061164        /* Start looping on the number of vertices: */
    1107         gauss=new GaussTria();
     1165        GaussTria* gauss=new GaussTria();
    11081166        for (int iv=0;iv<NUMVERTICES;iv++){
    11091167                gauss->GaussVertex(iv);
     
    11181176void Tria::GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue){
    11191177
    1120         IssmDouble     value[NUMVERTICES];
    1121         GaussTria *gauss = NULL;
    11221178        Input     *input = inputs->GetInput(enumtype);
    11231179
     
    11271183        /* Start looping on the number of vertices: */
    11281184        if (input){
    1129                 gauss=new GaussTria();
     1185                GaussTria* gauss=new GaussTria();
    11301186                for (int iv=0;iv<NUMVERTICES;iv++){
    11311187                        gauss->GaussVertex(iv);
    11321188                        input->GetInputValue(&pvalue[iv],gauss);
    11331189                }
     1190                delete gauss;
    11341191        }
    11351192        else{
    11361193                for (int iv=0;iv<NUMVERTICES;iv++) pvalue[iv]=defaultvalue;
    11371194        }
    1138 
    1139         /*clean-up*/
    1140         delete gauss;
    11411195}
    11421196/*}}}*/
     
    11441198void Tria::GetInputListOnVertices(IssmDouble* pvalue,int enumtype,IssmDouble defaultvalue,int index){
    11451199
    1146         IssmDouble     value[NUMVERTICES];
    1147         GaussTria *gauss = NULL;
    11481200        Input     *input = inputs->GetInput(enumtype);
    11491201
     
    11531205        /* Start looping on the number of vertices: */
    11541206        if (input){
    1155                 gauss=new GaussTria();
     1207                GaussTria* gauss=new GaussTria();
    11561208                for (int iv=0;iv<NUMVERTICES;iv++){
    11571209                        gauss->GaussVertex(iv);
    11581210                        input->GetInputValue(&pvalue[iv],gauss,index);
    11591211                }
     1212                delete gauss;
    11601213        }
    11611214        else{
    11621215                for (int iv=0;iv<NUMVERTICES;iv++) pvalue[iv]=defaultvalue;
    11631216        }
    1164 
    1165         /*clean-up*/
    1166         delete gauss;
    11671217}
    11681218/*}}}*/
     
    11801230}
    11811231/*}}}*/
    1182 /*FUNCTION Tria::GetSidList {{{*/
    1183 void  Tria::GetSidList(int* sidlist){
    1184         for(int i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->GetSidList();
     1232/*FUNCTION Tria::GetVertexPidList {{{*/
     1233void  Tria::GetVertexPidList(int* doflist){
     1234
     1235        int i;
     1236        for(i=0;i<3;i++) doflist[i]=nodes[i]->GetVertexPid();
     1237
     1238}
     1239/*}}}*/
     1240/*FUNCTION Tria::GetVertexSidList {{{*/
     1241void  Tria::GetVertexSidList(int* sidlist){
     1242        for(int i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->GetVertexSid();
    11851243}
    11861244/*}}}*/
     
    12431301void  Tria::GetVectorFromInputs(Vector<IssmDouble>* vector,int input_enum){
    12441302
    1245         int doflist1[NUMVERTICES];
     1303        int vertexpidlist[NUMVERTICES];
    12461304
    12471305        /*Get out if this is not an element input*/
     
    12491307
    12501308        /*Prepare index list*/
    1251         this->GetDofList1(&doflist1[0]);
     1309        this->GetVertexPidList(&vertexpidlist[0]);
    12521310
    12531311        /*Get input (either in element or material)*/
     
    12561314
    12571315        /*We found the enum.  Use its values to fill into the vector, using the vertices ids: */
    1258         input->GetVectorFromInputs(vector,&doflist1[0]);
     1316        input->GetVectorFromInputs(vector,&vertexpidlist[0]);
    12591317}
    12601318/*}}}*/
     
    12681326        }
    12691327        if(interp==P1Enum){
    1270                 int doflist1[NUMVERTICES];
     1328                int vertexpidlist[NUMVERTICES];
    12711329                int connectivity[NUMVERTICES];
    1272                 this->GetSidList(&doflist1[0]);
     1330                this->GetVertexSidList(&vertexpidlist[0]);
    12731331                this->GetConnectivityList(&connectivity[0]);
    1274                 elementresult->GetVectorFromResults(vector,&doflist1[0],&connectivity[0],NUMVERTICES);
     1332                elementresult->GetVectorFromResults(vector,&vertexpidlist[0],&connectivity[0],NUMVERTICES);
    12751333        }
    12761334        else if(interp==P0Enum){
     
    12841342/*FUNCTION Tria::Id {{{*/
    12851343int    Tria::Id(){
    1286        
     1344
    12871345        return id;
    12881346
     
    12911349/*FUNCTION Tria::Sid {{{*/
    12921350int    Tria::Sid(){
    1293        
     1351
    12941352        return sid;
    12951353
     
    13921450void  Tria::InputToResult(int enum_type,int step,IssmDouble time){
    13931451
    1394         int    i;
    13951452        Input *input = NULL;   
    13961453
    13971454        /*Go through all the input objects, and find the one corresponding to enum_type, if it exists: */
    1398         if (enum_type==MaterialsRheologyBbarEnum || enum_type==MaterialsRheologyZbarEnum) input=this->material->inputs->GetInput(enum_type);
    1399         else input=this->inputs->GetInput(enum_type);
     1455        if (enum_type==MaterialsRheologyBbarEnum || enum_type==MaterialsRheologyZbarEnum)
     1456         input=this->material->inputs->GetInput(enum_type);
     1457        else
     1458         input=this->inputs->GetInput(enum_type);
    14001459        //if (!input) _error_("Input " << EnumToStringx(enum_type) << " not found in tria->inputs");
    14011460        if(!input)return;
     
    14041463         * object out of the input, with the additional step and time information: */
    14051464        this->results->AddObject((Object*)input->SpawnResult(step,time));
    1406        
     1465
    14071466        #ifdef _HAVE_CONTROL_
    14081467        if(input->ObjectEnum()==ControlInputEnum){
     
    14521511        IssmDouble yts;
    14531512        int        num_cm_responses;
    1454    
     1513
    14551514        /*Get parameters: */
    14561515        iomodel->Constant(&yts,ConstantsYtsEnum);
     
    16871746                        /*Get values on the 3 vertices*/
    16881747                        for (int i=0;i<3;i++){
    1689                                 values[i]=vector[this->nodes[i]->GetVertexDof()];
     1748                                values[i]=vector[this->nodes[i]->GetVertexPid()];
    16901749                        }
    16911750
     
    17191778        /*Check that name is an element input*/
    17201779        if (!IsInput(name)) return;
    1721        
     1780
    17221781        if ((code==5) || (code==1)){ //boolean
    17231782                this->inputs->AddInput(new BoolInput(name,reCast<bool>(scalar)));
     
    17461805        int    numberofelements;
    17471806        IssmDouble yts;
    1748 
    17491807
    17501808        /*Fetch parameters: */
     
    18611919/*FUNCTION Tria::IsOnBed {{{*/
    18621920bool Tria::IsOnBed(){
    1863        
     1921
    18641922        bool onbed;
    18651923        inputs->GetInputValue(&onbed,MeshElementonbedEnum);
     
    19672025void  Tria::MigrateGroundingLine(IssmDouble* old_floating_ice,IssmDouble* sheet_ungrounding){
    19682026
    1969         int     i,migration_style,unground;
     2027        int     i,migration_style;
    19702028        bool    elementonshelf = false;
    19712029        IssmDouble  bed_hydro,yts,gl_melting_rate;
     
    19762034        /*Recover info at the vertices: */
    19772035        parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
     2036        parameters->FindParam(&gl_melting_rate,GroundinglineMeltingRateEnum);
    19782037        parameters->FindParam(&yts,ConstantsYtsEnum);
    19792038        GetInputListOnVertices(&h[0],ThicknessEnum);
     
    19842043        rho_ice=matpar->GetRhoIce();
    19852044        density=rho_ice/rho_water;
    1986        
     2045
    19872046        /*go through vertices, and update inputs, considering them to be TriaVertex type: */
    19882047        for(i=0;i<NUMVERTICES;i++){
     
    20252084                }
    20262085        }
    2027        
     2086
    20282087   /*Add basal melting rate if element just ungrounded*/
    20292088        if(!this->IsFloating() && elementonshelf==true){
     
    20382097        this->inputs->AddInput(new TriaP1Input(SurfaceEnum,&s[0]));
    20392098        this->inputs->AddInput(new TriaP1Input(BedEnum,&b[0]));
    2040 }
    2041 /*}}}*/
    2042 /*FUNCTION Tria::MyRank {{{*/
    2043 int    Tria::MyRank(void){
    2044         extern int my_rank;
    2045         return my_rank;
    20462099}
    20472100/*}}}*/
     
    20872140        /*recover pointer: */
    20882141        row=*prow;
    2089                
     2142
    20902143        for(i=0;i<3;i++) vertices_ids[i]=nodes[i]->GetVertexId(); //vertices id start at column 3 of the patch.
    20912144
     
    22692322        IssmDouble b_neg[NUMVERTICES];                          // Hs-SMB relation paremeter
    22702323        IssmDouble Hc[NUMVERTICES];                                     // elevation of transition between accumulation regime and ablation regime
     2324        IssmDouble Href[NUMVERTICES];                                   // reference elevation from which deviations are used to calculate the SMB adjustment
     2325        IssmDouble Smbref[NUMVERTICES];                         // reference SMB to which deviations are added
    22712326        IssmDouble smb_pos_max[NUMVERTICES];            // maximum SMB value in the accumulation regime
    22722327        IssmDouble smb_pos_min[NUMVERTICES];            // minimum SMB value in the accumulation regime
     
    22792334        /*Recover SmbGradients*/
    22802335        GetInputListOnVertices(&Hc[0],SurfaceforcingsHcEnum);
     2336        GetInputListOnVertices(&Href[0],SurfaceforcingsHrefEnum);
     2337        GetInputListOnVertices(&Smbref[0],SurfaceforcingsSmbrefEnum);
    22812338        GetInputListOnVertices(&smb_pos_max[0],SurfaceforcingsSmbPosMaxEnum);
    22822339        GetInputListOnVertices(&smb_pos_min[0],SurfaceforcingsSmbPosMinEnum);
     
    22852342        GetInputListOnVertices(&a_neg[0],SurfaceforcingsANegEnum);
    22862343        GetInputListOnVertices(&b_neg[0],SurfaceforcingsBNegEnum);
    2287        
     2344
    22882345   /*Recover surface elevatio at vertices: */
    22892346        GetInputListOnVertices(&h[0],ThicknessEnum);
     
    22932350   rho_ice=matpar->GetRhoIce();
    22942351   rho_water=matpar->GetRhoFreshwater();
    2295                        
     2352
    22962353   // loop over all vertices
    22972354   for(i=0;i<NUMVERTICES;i++){
    22982355     if(s[i]>Hc[i]){
    2299             smb[i]=a_pos[i]+b_pos[i]*s[i];
    2300                  if(smb[i]>smb_pos_max[i]){smb[i]=smb_pos_max[i];}
    2301                  if(smb[i]<smb_pos_min[i]){smb[i]=smb_pos_min[i];}
     2356                  if(Href[i]>Hc[i]){smb[i]=Smbref[i]+b_pos[i]*(s[i]-Href[i]);}
     2357                  if(Href[i]<=Hc[i]){smb[i]=a_pos[i]+b_pos[i]*s[i];}
     2358                  if(smb[i]>smb_pos_max[i]){smb[i]=smb_pos_max[i];}
     2359                  if(smb[i]<smb_pos_min[i]){smb[i]=smb_pos_min[i];}
    23022360          }
    23032361          else{
    2304             smb[i]=a_neg[i]+b_neg[i]*s[i];
     2362                  if(Href[i]>Hc[i]){smb[i]=a_neg[i]+b_neg[i]*s[i];}
     2363                  if(Href[i]<=Hc[i]){smb[i]=Smbref[i]+b_neg[i]*(s[i]-Href[i]);}
    23052364          }
    23062365          smb[i]=smb[i]/rho_ice;      // SMB in m/y ice         
    2307         }  //end of the loop over the vertices
     2366  /*   printf("s %e \n",s[i]);
     2367     printf("Hsref %e \n",Href[i]);
     2368     printf("Hc %e \n",Hc[i]);
     2369     printf("Smbref %e \n",Smbref[i]);
     2370     printf("b_neg %e \n",b_neg[i]);
     2371     printf("smb %e \n",smb[i]);
     2372          _error_("stop-in-code"); */
     2373                }  //end of the loop over the vertices
    23082374          /*Update inputs*/
    23092375          this->inputs->AddInput(new TriaP1Input(SurfaceforcingsMassBalanceEnum,&smb[0]));
     
    23122378/*FUNCTION Tria::SetCurrentConfiguration {{{*/
    23132379void  Tria::SetCurrentConfiguration(Elements* elementsin, Loads* loadsin, DataSet* nodesin, Materials* materialsin, Parameters* parametersin){
    2314        
     2380
    23152381        /*go into parameters and get the analysis_counter: */
    23162382        int analysis_counter;
     
    25332599                if (reCast<bool>(vertices_potentially_ungrounding[nodes[i]->Sid()])){
    25342600                        vec_nodes_on_iceshelf->SetValue(nodes[i]->Sid(),1,INS_VAL);
    2535                
     2601
    25362602                        /*If node was not on ice shelf, we flipped*/
    25372603                        if(nodes_on_iceshelf[nodes[i]->Sid()]==0){
     
    25742640IssmDouble Tria::MassFlux( IssmDouble* segment,bool process_units){
    25752641
    2576         const int    numdofs=2;
    2577 
    2578         int        i,dim;
    2579         IssmDouble     mass_flux=0;
    2580         IssmDouble     xyz_list[NUMVERTICES][3];
    2581         IssmDouble     normal[2];
    2582         IssmDouble     length,rho_ice;
    2583         IssmDouble     x1,y1,x2,y2,h1,h2;
    2584         IssmDouble     vx1,vx2,vy1,vy2;
     2642        const int  numdofs=2;
     2643        int        dim;
     2644        IssmDouble mass_flux=0;
     2645        IssmDouble xyz_list[NUMVERTICES][3];
     2646        IssmDouble normal[2];
     2647        IssmDouble length,rho_ice;
     2648        IssmDouble x1,y1,x2,y2,h1,h2;
     2649        IssmDouble vx1,vx2,vy1,vy2;
    25852650        GaussTria* gauss_1=NULL;
    25862651        GaussTria* gauss_2=NULL;
     
    28422907        smb_input->GetInputAverage(&smb);                                                                                                                                                                                               // average smb on element in m ice s-1
    28432908   Total_Smb=rho_ice*base*smb;                                                                                                                                                                                                                  // smb on element in kg s-1
    2844        
     2909
    28452910        /*Process units: */
    28462911        Total_Smb=UnitConversion(Total_Smb,IuToExtEnum,TotalSmbEnum);                                                                                                                           // smb on element in GigaTon yr-1
    2847        
     2912
    28482913        /*Return: */
    28492914        return Total_Smb;
     
    28602925        ElementMatrix* Ke2=CreateKMatrixDiagnosticMacAyealFriction();
    28612926        ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
    2862        
     2927
    28632928        /*clean-up and return*/
    28642929        delete Ke1;
     
    28742939
    28752940        /*Intermediaries*/
    2876         int        i,j,ig;
    2877         IssmDouble     xyz_list[NUMVERTICES][3];
    2878         IssmDouble     viscosity,newviscosity,oldviscosity;
    2879         IssmDouble     viscosity_overshoot,thickness,Jdet;
    2880         IssmDouble     epsilon[3],oldepsilon[3];    /* epsilon=[exx,eyy,exy];    */
    2881         IssmDouble     B[3][numdof];
    2882         IssmDouble     Bprime[3][numdof];
    2883         IssmDouble     D[3][3]   = {0.0};
    2884         IssmDouble     D_scalar;
     2941        int        i,j;
     2942        IssmDouble xyz_list[NUMVERTICES][3];
     2943        IssmDouble viscosity,newviscosity,oldviscosity;
     2944        IssmDouble viscosity_overshoot,thickness,Jdet;
     2945        IssmDouble epsilon[3],oldepsilon[3];    /* epsilon=[exx,eyy,exy];    */
     2946        IssmDouble B[3][numdof];
     2947        IssmDouble Bprime[3][numdof];
     2948        IssmDouble D[3][3]   = {0.0};
     2949        IssmDouble D_scalar;
    28852950        GaussTria *gauss = NULL;
    28862951
     
    28992964        /* Start  looping on the number of gaussian points: */
    29002965        gauss=new GaussTria(2);
    2901         for (ig=gauss->begin();ig<gauss->end();ig++){
     2966        for(int ig=gauss->begin();ig<gauss->end();ig++){
    29022967
    29032968                gauss->GaussPoint(ig);
     
    29383003
    29393004        /*Intermediaries*/
    2940         int        i,j,ig;
     3005        int        i,j;
    29413006        int        analysis_type;
    2942         IssmDouble     MAXSLOPE  = .06; // 6 %
    2943         IssmDouble     MOUNTAINKEXPONENT = 10;
    2944         IssmDouble     slope_magnitude,alpha2;
    2945         IssmDouble     Jdet;
    2946         IssmDouble     L[2][numdof];
    2947         IssmDouble     DL[2][2]  = {{ 0,0 },{0,0}};
    2948         IssmDouble     DL_scalar;
    2949         IssmDouble     slope[2]  = {0.0,0.0};
    2950         IssmDouble     xyz_list[NUMVERTICES][3];
     3007        IssmDouble MAXSLOPE  = .06; // 6 %
     3008        IssmDouble MOUNTAINKEXPONENT = 10;
     3009        IssmDouble slope_magnitude,alpha2;
     3010        IssmDouble Jdet;
     3011        IssmDouble L[2][numdof];
     3012        IssmDouble DL[2][2]  = {{ 0,0 },{0,0}};
     3013        IssmDouble DL_scalar;
     3014        IssmDouble slope[2]  = {0.0,0.0};
     3015        IssmDouble xyz_list[NUMVERTICES][3];
    29513016        Friction  *friction = NULL;
    29523017        GaussTria *gauss    = NULL;
     
    29693034        /* Start  looping on the number of gaussian points: */
    29703035        gauss=new GaussTria(2);
    2971         for (ig=gauss->begin();ig<gauss->end();ig++){
     3036        for(int ig=gauss->begin();ig<gauss->end();ig++){
    29723037
    29733038                gauss->GaussPoint(ig);
     
    29843049                DL_scalar=alpha2*gauss->weight*Jdet;
    29853050                for (i=0;i<2;i++) DL[i][i]=DL_scalar;
    2986                
     3051
    29873052                TripleMultiply( &L[0][0],2,numdof,1,
    29883053                                        &DL[0][0],2,2,0,
     
    30283093
    30293094        /*Intermediaries */
    3030         int            i,j,ig;
    3031         IssmDouble         driving_stress_baseline,thickness;
    3032         IssmDouble         Jdet;
    3033         IssmDouble         xyz_list[NUMVERTICES][3];
    3034         IssmDouble         slope[2];
    3035         IssmDouble         basis[3];
    3036         IssmDouble         pe_g_gaussian[numdof];
     3095        int            i,j;
     3096        IssmDouble     driving_stress_baseline,thickness;
     3097        IssmDouble     Jdet;
     3098        IssmDouble     xyz_list[NUMVERTICES][3];
     3099        IssmDouble     slope[2];
     3100        IssmDouble     basis[3];
     3101        IssmDouble     pe_g_gaussian[numdof];
    30373102        GaussTria*     gauss=NULL;
    30383103
     
    30483113        /* Start  looping on the number of gaussian points: */
    30493114        gauss=new GaussTria(2);
    3050         for(ig=gauss->begin();ig<gauss->end();ig++){
     3115        for(int ig=gauss->begin();ig<gauss->end();ig++){
    30513116
    30523117                gauss->GaussPoint(ig);
     
    31323197
    31333198        /*Intermediaries */
    3134         int        i,j,ig;
    3135         IssmDouble     xyz_list[NUMVERTICES][3];
    3136         IssmDouble     Jdet,thickness;
    3137         IssmDouble     eps1dotdphii,eps1dotdphij;
    3138         IssmDouble     eps2dotdphii,eps2dotdphij;
    3139         IssmDouble     mu_prime;
    3140         IssmDouble     epsilon[3];/* epsilon=[exx,eyy,exy];*/
    3141         IssmDouble     eps1[2],eps2[2];
    3142         IssmDouble     phi[NUMVERTICES];
    3143         IssmDouble     dphi[2][NUMVERTICES];
     3199        int        i,j;
     3200        IssmDouble xyz_list[NUMVERTICES][3];
     3201        IssmDouble Jdet,thickness;
     3202        IssmDouble eps1dotdphii,eps1dotdphij;
     3203        IssmDouble eps2dotdphii,eps2dotdphij;
     3204        IssmDouble mu_prime;
     3205        IssmDouble epsilon[3];/* epsilon=[exx,eyy,exy];*/
     3206        IssmDouble eps1[2],eps2[2];
     3207        IssmDouble phi[NUMVERTICES];
     3208        IssmDouble dphi[2][NUMVERTICES];
    31443209        GaussTria *gauss=NULL;
    31453210
     
    31553220        /* Start  looping on the number of gaussian points: */
    31563221        gauss=new GaussTria(2);
    3157         for (ig=gauss->begin();ig<gauss->end();ig++){
     3222        for(int ig=gauss->begin();ig<gauss->end();ig++){
    31583223
    31593224                gauss->GaussPoint(ig);
     
    32713336/*FUNCTION Tria::InputUpdateFromSolutionDiagnosticHoriz {{{*/
    32723337void  Tria::InputUpdateFromSolutionDiagnosticHoriz(IssmDouble* solution){
    3273        
     3338
    32743339        const int numdof=NDOF2*NUMVERTICES;
    32753340
     
    32843349        IssmDouble    pressure[NUMVERTICES];
    32853350        IssmDouble    thickness[NUMVERTICES];
    3286        
     3351
    32873352        /*Get dof list: */
    32883353        GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
     
    33343399/*FUNCTION Tria::InputUpdateFromSolutionDiagnosticHutter {{{*/
    33353400void  Tria::InputUpdateFromSolutionDiagnosticHutter(IssmDouble* solution){
    3336        
     3401
    33373402        const int numdof=NDOF2*NUMVERTICES;
    3338        
     3403
    33393404        int       i;
    33403405        int*      doflist=NULL;
     
    33473412        IssmDouble    pressure[NUMVERTICES];
    33483413        IssmDouble    thickness[NUMVERTICES];
    3349        
     3414
    33503415        /*Get dof list: */
    33513416        GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
     
    34323497void Tria::ControlInputGetGradient(Vector<IssmDouble>* gradient,int enum_type,int control_index){
    34333498
    3434         int doflist1[NUMVERTICES];
     3499        int vertexpidlist[NUMVERTICES];
    34353500        Input* input=NULL;
    34363501
     
    34443509        if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
    34453510
    3446         GradientIndexing(&doflist1[0],control_index);
    3447         ((ControlInput*)input)->GetGradient(gradient,&doflist1[0]);
     3511        GradientIndexing(&vertexpidlist[0],control_index);
     3512        ((ControlInput*)input)->GetGradient(gradient,&vertexpidlist[0]);
    34483513
    34493514}/*}}}*/
     
    34673532void Tria::ControlInputSetGradient(IssmDouble* gradient,int enum_type,int control_index){
    34683533
    3469         int    doflist1[NUMVERTICES];
     3534        int    vertexpidlist[NUMVERTICES];
    34703535        IssmDouble grad_list[NUMVERTICES];
    34713536        Input* grad_input=NULL;
     
    34813546        if (input->ObjectEnum()!=ControlInputEnum) _error_("Input " << EnumToStringx(enum_type) << " is not a ControlInput");
    34823547
    3483         GradientIndexing(&doflist1[0],control_index);
    3484         for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[doflist1[i]];
     3548        GradientIndexing(&vertexpidlist[0],control_index);
     3549        for(int i=0;i<NUMVERTICES;i++) grad_list[i]=gradient[vertexpidlist[i]];
    34853550        grad_input=new TriaP1Input(GradientEnum,grad_list);
    34863551
     
    35553620void  Tria::GradjBGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index){
    35563621
    3557         int        i,ig;
    3558         int        doflist1[NUMVERTICES];
    3559         IssmDouble     Jdet,weight;
    3560         IssmDouble     xyz_list[NUMVERTICES][3];
    3561         IssmDouble     dbasis[NDOF2][NUMVERTICES];
    3562         IssmDouble     dk[NDOF2];
    3563         IssmDouble     grade_g[NUMVERTICES]={0.0};
     3622        int        i;
     3623        int        vertexpidlist[NUMVERTICES];
     3624        IssmDouble Jdet,weight;
     3625        IssmDouble xyz_list[NUMVERTICES][3];
     3626        IssmDouble dbasis[NDOF2][NUMVERTICES];
     3627        IssmDouble dk[NDOF2];
     3628        IssmDouble grade_g[NUMVERTICES]={0.0};
    35643629        GaussTria  *gauss=NULL;
    35653630
    35663631        /*Retrieve all inputs we will be needing: */
    35673632        GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
    3568         GradientIndexing(&doflist1[0],control_index);
     3633        GradientIndexing(&vertexpidlist[0],control_index);
    35693634        Input* rheologyb_input=material->inputs->GetInput(MaterialsRheologyBbarEnum); _assert_(rheologyb_input);
    35703635        Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                _assert_(weights_input);
     
    35723637        /* Start  looping on the number of gaussian points: */
    35733638        gauss=new GaussTria(2);
    3574         for (ig=gauss->begin();ig<gauss->end();ig++){
     3639        for(int ig=gauss->begin();ig<gauss->end();ig++){
    35753640
    35763641                gauss->GaussPoint(ig);
     
    35863651                for (i=0;i<NUMVERTICES;i++) grade_g[i]+=-weight*Jdet*gauss->weight*(dbasis[0][i]*dk[0]+dbasis[1][i]*dk[1]);
    35873652        }
    3588         gradient->SetValues(NUMVERTICES,doflist1,grade_g,ADD_VAL);
     3653        gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
    35893654
    35903655        /*Clean up and return*/
     
    35953660void  Tria::GradjZGradient(Vector<IssmDouble>* gradient,int weight_index,int control_index){
    35963661
    3597         int        i,ig;
    3598         int        doflist1[NUMVERTICES];
    3599         IssmDouble     Jdet,weight;
    3600         IssmDouble     xyz_list[NUMVERTICES][3];
    3601         IssmDouble     dbasis[NDOF2][NUMVERTICES];
    3602         IssmDouble     dk[NDOF2];
    3603         IssmDouble     grade_g[NUMVERTICES]={0.0};
     3662        int        i;
     3663        int        vertexpidlist[NUMVERTICES];
     3664        IssmDouble Jdet,weight;
     3665        IssmDouble xyz_list[NUMVERTICES][3];
     3666        IssmDouble dbasis[NDOF2][NUMVERTICES];
     3667        IssmDouble dk[NDOF2];
     3668        IssmDouble grade_g[NUMVERTICES]={0.0};
    36043669        GaussTria  *gauss=NULL;
    36053670
    36063671        /*Retrieve all inputs we will be needing: */
    36073672        GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
    3608         GradientIndexing(&doflist1[0],control_index);
     3673        GradientIndexing(&vertexpidlist[0],control_index);
    36093674        Input* rheologyz_input=material->inputs->GetInput(MaterialsRheologyZbarEnum); _assert_(rheologyz_input);
    36103675        Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                _assert_(weights_input);
     
    36123677        /* Start  looping on the number of gaussian points: */
    36133678        gauss=new GaussTria(2);
    3614         for (ig=gauss->begin();ig<gauss->end();ig++){
     3679        for(int ig=gauss->begin();ig<gauss->end();ig++){
    36153680
    36163681                gauss->GaussPoint(ig);
     
    36263691                for (i=0;i<NUMVERTICES;i++) grade_g[i]+=-weight*Jdet*gauss->weight*(dbasis[0][i]*dk[0]+dbasis[1][i]*dk[1]);
    36273692        }
    3628         gradient->SetValues(NUMVERTICES,doflist1,grade_g,ADD_VAL);
     3693        gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
    36293694
    36303695        /*Clean up and return*/
     
    36363701
    36373702        /*Intermediaries*/
    3638         int        i,ig;
     3703        int        i;
    36393704        int        doflist[NUMVERTICES];
    3640         IssmDouble     vx,vy,lambda,mu,thickness,Jdet;
    3641         IssmDouble     viscosity_complement;
    3642         IssmDouble     dvx[NDOF2],dvy[NDOF2],dadjx[NDOF2],dadjy[NDOF2],dB[NDOF2];
    3643         IssmDouble     xyz_list[NUMVERTICES][3];
    3644         IssmDouble     basis[3],epsilon[3];
    3645         IssmDouble     grad[NUMVERTICES]={0.0};
     3705        IssmDouble vx,vy,lambda,mu,thickness,Jdet;
     3706        IssmDouble viscosity_complement;
     3707        IssmDouble dvx[NDOF2],dvy[NDOF2],dadjx[NDOF2],dadjy[NDOF2],dB[NDOF2];
     3708        IssmDouble xyz_list[NUMVERTICES][3];
     3709        IssmDouble basis[3],epsilon[3];
     3710        IssmDouble grad[NUMVERTICES]={0.0};
    36463711        GaussTria *gauss = NULL;
    36473712
     
    36603725        /* Start  looping on the number of gaussian points: */
    36613726        gauss=new GaussTria(4);
    3662         for (ig=gauss->begin();ig<gauss->end();ig++){
     3727        for(int ig=gauss->begin();ig<gauss->end();ig++){
    36633728
    36643729                gauss->GaussPoint(ig);
     
    36933758
    36943759        /*Intermediaries*/
    3695         int        i,ig;
     3760        int        i;
    36963761        int        doflist[NUMVERTICES];
    3697         IssmDouble     vx,vy,lambda,mu,thickness,Jdet;
    3698         IssmDouble     viscosity_complement;
    3699         IssmDouble     dvx[NDOF2],dvy[NDOF2],dadjx[NDOF2],dadjy[NDOF2],dZ[NDOF2];
    3700         IssmDouble     xyz_list[NUMVERTICES][3];
    3701         IssmDouble     basis[3],epsilon[3];
    3702         IssmDouble     grad[NUMVERTICES]={0.0};
     3762        IssmDouble vx,vy,lambda,mu,thickness,Jdet;
     3763        IssmDouble viscosity_complement;
     3764        IssmDouble dvx[NDOF2],dvy[NDOF2],dadjx[NDOF2],dadjy[NDOF2],dZ[NDOF2];
     3765        IssmDouble xyz_list[NUMVERTICES][3];
     3766        IssmDouble basis[3],epsilon[3];
     3767        IssmDouble grad[NUMVERTICES]={0.0};
    37033768        GaussTria *gauss = NULL;
    37043769
     
    37173782        /* Start  looping on the number of gaussian points: */
    37183783        gauss=new GaussTria(4);
    3719         for (ig=gauss->begin();ig<gauss->end();ig++){
     3784        for(int ig=gauss->begin();ig<gauss->end();ig++){
    37203785
    37213786                gauss->GaussPoint(ig);
     
    37493814void  Tria::GradjDragMacAyeal(Vector<IssmDouble>* gradient,int control_index){
    37503815
    3751         int        i,ig;
     3816        int        i;
    37523817        int        analysis_type;
    3753         int        doflist1[NUMVERTICES];
     3818        int        vertexpidlist[NUMVERTICES];
    37543819        int        connectivity[NUMVERTICES];
    3755         IssmDouble     vx,vy,lambda,mu,alpha_complement,Jdet;
    3756         IssmDouble     bed,thickness,Neff,drag;
    3757         IssmDouble     xyz_list[NUMVERTICES][3];
    3758         IssmDouble     dk[NDOF2];
    3759         IssmDouble     grade_g[NUMVERTICES]={0.0};
    3760         IssmDouble     grade_g_gaussian[NUMVERTICES];
    3761         IssmDouble     basis[3];
    3762         IssmDouble     epsilon[3]; /* epsilon=[exx,eyy,exy];*/
     3820        IssmDouble vx,vy,lambda,mu,alpha_complement,Jdet;
     3821        IssmDouble bed,thickness,Neff,drag;
     3822        IssmDouble xyz_list[NUMVERTICES][3];
     3823        IssmDouble dk[NDOF2];
     3824        IssmDouble grade_g[NUMVERTICES]={0.0};
     3825        IssmDouble grade_g_gaussian[NUMVERTICES];
     3826        IssmDouble basis[3];
     3827        IssmDouble epsilon[3]; /* epsilon=[exx,eyy,exy];*/
    37633828        Friction*  friction=NULL;
    37643829        GaussTria  *gauss=NULL;
     
    37693834        parameters->FindParam(&analysis_type,AnalysisTypeEnum);
    37703835        GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
    3771         GradientIndexing(&doflist1[0],control_index);
     3836        GradientIndexing(&vertexpidlist[0],control_index);
    37723837        this->GetConnectivityList(&connectivity[0]);
    37733838
     
    37843849        /* Start  looping on the number of gaussian points: */
    37853850        gauss=new GaussTria(4);
    3786         for (ig=gauss->begin();ig<gauss->end();ig++){
     3851        for(int ig=gauss->begin();ig<gauss->end();ig++){
    37873852
    37883853                gauss->GaussPoint(ig);
     
    37933858                /*Build alpha_complement_list: */
    37943859                friction->GetAlphaComplement(&alpha_complement, gauss,VxEnum,VyEnum,VzEnum);
    3795        
     3860
    37963861                dragcoefficient_input->GetInputValue(&drag, gauss);
    37973862                adjointx_input->GetInputValue(&lambda, gauss);
     
    38053870                        grade_g_gaussian[i]=-2*drag*alpha_complement*((lambda*vx+mu*vy))*Jdet*gauss->weight*basis[i];
    38063871                }
    3807                
     3872
    38083873                /*Add gradje_g_gaussian vector to gradje_g: */
    38093874                for(i=0;i<NUMVERTICES;i++){
     
    38273892        /*End Analytical gradient*/
    38283893
    3829         gradient->SetValues(NUMVERTICES,doflist1,grade_g,ADD_VAL);
     3894        gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
    38303895
    38313896        /*Clean up and return*/
     
    38373902void  Tria::GradjDragGradient(Vector<IssmDouble>* gradient, int weight_index,int control_index){
    38383903
    3839         int        i,ig;
    3840         int        doflist1[NUMVERTICES];
    3841         IssmDouble     Jdet,weight;
    3842         IssmDouble     xyz_list[NUMVERTICES][3];
    3843         IssmDouble     dbasis[NDOF2][NUMVERTICES];
    3844         IssmDouble     dk[NDOF2];
    3845         IssmDouble     grade_g[NUMVERTICES]={0.0};
     3904        int        i;
     3905        int        vertexpidlist[NUMVERTICES];
     3906        IssmDouble Jdet,weight;
     3907        IssmDouble xyz_list[NUMVERTICES][3];
     3908        IssmDouble dbasis[NDOF2][NUMVERTICES];
     3909        IssmDouble dk[NDOF2];
     3910        IssmDouble grade_g[NUMVERTICES]={0.0};
    38463911        GaussTria  *gauss=NULL;
    38473912
     
    38493914        if(IsFloating())return;
    38503915        GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
    3851         GradientIndexing(&doflist1[0],control_index);
     3916        GradientIndexing(&vertexpidlist[0],control_index);
    38523917        Input* dragcoefficient_input=inputs->GetInput(FrictionCoefficientEnum); _assert_(dragcoefficient_input);
    38533918        Input* weights_input=inputs->GetInput(InversionCostFunctionsCoefficientsEnum);                 _assert_(weights_input);
     
    38553920        /* Start  looping on the number of gaussian points: */
    38563921        gauss=new GaussTria(2);
    3857         for (ig=gauss->begin();ig<gauss->end();ig++){
     3922        for(int ig=gauss->begin();ig<gauss->end();ig++){
    38583923
    38593924                gauss->GaussPoint(ig);
     
    38723937                }
    38733938        }
    3874         gradient->SetValues(NUMVERTICES,doflist1,grade_g,ADD_VAL);
     3939        gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
    38753940
    38763941        /*Clean up and return*/
     
    38823947
    38833948        /*Intermediaries*/
    3884         int    doflist1[NUMVERTICES];
     3949        int    vertexpidlist[NUMVERTICES];
    38853950        IssmDouble lambda[NUMVERTICES];
    38863951        IssmDouble gradient_g[NUMVERTICES];
    38873952
    38883953        /*Compute Gradient*/
    3889         GradientIndexing(&doflist1[0],control_index);
     3954        GradientIndexing(&vertexpidlist[0],control_index);
    38903955        GetInputListOnVertices(&lambda[0],AdjointEnum);
    38913956        for(int i=0;i<NUMVERTICES;i++) gradient_g[i]=-lambda[i];
    38923957
    3893         gradient->SetValues(NUMVERTICES,doflist1,gradient_g,INS_VAL);
     3958        gradient->SetValues(NUMVERTICES,vertexpidlist,gradient_g,INS_VAL);
    38943959}
    38953960/*}}}*/
     
    38983963
    38993964        /*Intermediaries*/
    3900         int        i,ig;
    3901         int        doflist1[NUMVERTICES];
    3902         IssmDouble     thickness,Jdet;
    3903         IssmDouble     basis[3];
    3904         IssmDouble     Dlambda[2],dp[2];
    3905         IssmDouble     xyz_list[NUMVERTICES][3];
    3906         IssmDouble     grade_g[NUMVERTICES] = {0.0};
     3965        int        i;
     3966        int        vertexpidlist[NUMVERTICES];
     3967        IssmDouble thickness,Jdet;
     3968        IssmDouble basis[3];
     3969        IssmDouble Dlambda[2],dp[2];
     3970        IssmDouble xyz_list[NUMVERTICES][3];
     3971        IssmDouble grade_g[NUMVERTICES] = {0.0};
    39073972        GaussTria *gauss                = NULL;
    39083973
    39093974        /* Get node coordinates and dof list: */
    39103975        GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
    3911         GradientIndexing(&doflist1[0],control_index);
     3976        GradientIndexing(&vertexpidlist[0],control_index);
    39123977
    39133978        /*Retrieve all inputs we will be needing: */
     
    39173982        /* Start  looping on the number of gaussian points: */
    39183983        gauss=new GaussTria(2);
    3919         for (ig=gauss->begin();ig<gauss->end();ig++){
     3984        for(int ig=gauss->begin();ig<gauss->end();ig++){
    39203985
    39213986                gauss->GaussPoint(ig);
     
    39233988                GetJacobianDeterminant2d(&Jdet, &xyz_list[0][0],gauss);
    39243989                GetNodalFunctions(basis, gauss);
    3925                
     3990
    39263991                adjoint_input->GetInputDerivativeValue(&Dlambda[0],&xyz_list[0][0],gauss);
    39273992                thickness_input->GetInputValue(&thickness, gauss);
     
    39313996        }
    39323997
    3933         gradient->SetValues(NUMVERTICES,doflist1,grade_g,ADD_VAL);
     3998        gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
    39343999
    39354000        /*Clean up and return*/
     
    39414006
    39424007        /*Intermediaries*/
    3943         int        i,ig;
    3944         int        doflist1[NUMVERTICES];
    3945         IssmDouble     thickness,Jdet;
    3946         IssmDouble     basis[3];
    3947         IssmDouble     Dlambda[2],dp[2];
    3948         IssmDouble     xyz_list[NUMVERTICES][3];
    3949         IssmDouble     grade_g[NUMVERTICES] = {0.0};
     4008        int        i;
     4009        int        vertexpidlist[NUMVERTICES];
     4010        IssmDouble thickness,Jdet;
     4011        IssmDouble basis[3];
     4012        IssmDouble Dlambda[2],dp[2];
     4013        IssmDouble xyz_list[NUMVERTICES][3];
     4014        IssmDouble grade_g[NUMVERTICES] = {0.0};
    39504015        GaussTria *gauss                = NULL;
    39514016
    39524017        /* Get node coordinates and dof list: */
    39534018        GetVerticesCoordinates(&xyz_list[0][0], nodes, NUMVERTICES);
    3954         GradientIndexing(&doflist1[0],control_index);
     4019        GradientIndexing(&vertexpidlist[0],control_index);
    39554020
    39564021        /*Retrieve all inputs we will be needing: */
     
    39604025        /* Start  looping on the number of gaussian points: */
    39614026        gauss=new GaussTria(2);
    3962         for (ig=gauss->begin();ig<gauss->end();ig++){
     4027        for(int ig=gauss->begin();ig<gauss->end();ig++){
    39634028
    39644029                gauss->GaussPoint(ig);
     
    39734038                for(i=0;i<NUMVERTICES;i++) grade_g[i]+=thickness*Dlambda[1]*Jdet*gauss->weight*basis[i];
    39744039        }
    3975         gradient->SetValues(NUMVERTICES,doflist1,grade_g,ADD_VAL);
     4040        gradient->SetValues(NUMVERTICES,vertexpidlist,grade_g,ADD_VAL);
    39764041
    39774042        /*Clean up and return*/
     
    39884053        /*get gradient indices*/
    39894054        for(int i=0;i<NUMVERTICES;i++){
    3990                 indexing[i]=num_controls*this->nodes[i]->GetVertexDof() + control_index;
     4055                indexing[i]=num_controls*this->nodes[i]->GetVertexPid() + control_index;
    39914056        }
    39924057
     
    39974062
    39984063        /* Intermediaries */
    3999         int        ig;
    4000         IssmDouble     Jelem = 0;
    4001         IssmDouble     weight;
    4002         IssmDouble     Jdet;
    4003         IssmDouble     xyz_list[NUMVERTICES][3];
    4004         IssmDouble     dp[NDOF2];
     4064        IssmDouble Jelem = 0;
     4065        IssmDouble weight;
     4066        IssmDouble Jdet;
     4067        IssmDouble xyz_list[NUMVERTICES][3];
     4068        IssmDouble dp[NDOF2];
    40054069        GaussTria *gauss = NULL;
    40064070
     
    40174081        /* Start looping on the number of gaussian points: */
    40184082        gauss=new GaussTria(2);
    4019         for (ig=gauss->begin();ig<gauss->end();ig++){
     4083        for(int ig=gauss->begin();ig<gauss->end();ig++){
    40204084
    40214085                gauss->GaussPoint(ig);
     
    40404104IssmDouble Tria::SurfaceAverageVelMisfit(bool process_units,int weight_index){
    40414105
    4042         const int    numdof=2*NUMVERTICES;
    4043 
    4044         int        i,ig;
    4045         IssmDouble     Jelem=0,S,Jdet;
    4046         IssmDouble     misfit;
    4047         IssmDouble     vx,vy,vxobs,vyobs,weight;
    4048         IssmDouble     xyz_list[NUMVERTICES][3];
     4106        IssmDouble Jelem=0,S,Jdet;
     4107        IssmDouble misfit;
     4108        IssmDouble vx,vy,vxobs,vyobs,weight;
     4109        IssmDouble xyz_list[NUMVERTICES][3];
    40494110        GaussTria *gauss=NULL;
    40504111
     
    40654126        /* Start  looping on the number of gaussian points: */
    40664127        gauss=new GaussTria(3);
    4067         for (ig=gauss->begin();ig<gauss->end();ig++){
     4128        for(int ig=gauss->begin();ig<gauss->end();ig++){
    40684129
    40694130                gauss->GaussPoint(ig);
     
    41014162IssmDouble Tria::SurfaceLogVelMisfit(bool process_units,int weight_index){
    41024163
    4103         const int    numdof=NDOF2*NUMVERTICES;
    4104 
    4105         int        i,ig;
    4106         IssmDouble     Jelem=0;
    4107         IssmDouble     misfit,Jdet;
    4108         IssmDouble     epsvel=2.220446049250313e-16;
    4109         IssmDouble     meanvel=3.170979198376458e-05; /*1000 m/yr*/
    4110         IssmDouble     velocity_mag,obs_velocity_mag;
    4111         IssmDouble     xyz_list[NUMVERTICES][3];
    4112         IssmDouble     vx,vy,vxobs,vyobs,weight;
     4164        IssmDouble Jelem=0;
     4165        IssmDouble misfit,Jdet;
     4166        IssmDouble epsvel=2.220446049250313e-16;
     4167        IssmDouble meanvel=3.170979198376458e-05; /*1000 m/yr*/
     4168        IssmDouble velocity_mag,obs_velocity_mag;
     4169        IssmDouble xyz_list[NUMVERTICES][3];
     4170        IssmDouble vx,vy,vxobs,vyobs,weight;
    41134171        GaussTria *gauss=NULL;
    41144172
     
    41284186        /* Start  looping on the number of gaussian points: */
    41294187        gauss=new GaussTria(4);
    4130         for (ig=gauss->begin();ig<gauss->end();ig++){
     4188        for(int ig=gauss->begin();ig<gauss->end();ig++){
    41314189
    41324190                gauss->GaussPoint(ig);
     
    41664224IssmDouble Tria::SurfaceLogVxVyMisfit(bool process_units,int weight_index){
    41674225
    4168         const int    numdof=NDOF2*NUMVERTICES;
    4169 
    4170         int        i,ig;
    41714226        int        fit=-1;
    4172         IssmDouble     Jelem=0, S=0;
    4173         IssmDouble     epsvel=2.220446049250313e-16;
    4174         IssmDouble     meanvel=3.170979198376458e-05; /*1000 m/yr*/
    4175         IssmDouble     misfit, Jdet;
    4176         IssmDouble     vx,vy,vxobs,vyobs,weight;
    4177         IssmDouble     xyz_list[NUMVERTICES][3];
     4227        IssmDouble Jelem=0, S=0;
     4228        IssmDouble epsvel=2.220446049250313e-16;
     4229        IssmDouble meanvel=3.170979198376458e-05; /*1000 m/yr*/
     4230        IssmDouble misfit, Jdet;
     4231        IssmDouble vx,vy,vxobs,vyobs,weight;
     4232        IssmDouble xyz_list[NUMVERTICES][3];
    41784233        GaussTria *gauss=NULL;
    41794234
     
    41904245        Input* vxobs_input  =inputs->GetInput(InversionVxObsEnum);     _assert_(vxobs_input);
    41914246        Input* vyobs_input  =inputs->GetInput(InversionVyObsEnum);     _assert_(vyobs_input);
    4192        
     4247
    41934248        /* Start  looping on the number of gaussian points: */
    41944249        gauss=new GaussTria(4);
    4195         for (ig=gauss->begin();ig<gauss->end();ig++){
     4250        for(int ig=gauss->begin();ig<gauss->end();ig++){
    41964251
    41974252                gauss->GaussPoint(ig);
     
    42324287IssmDouble Tria::SurfaceAbsVelMisfit(bool process_units,int weight_index){
    42334288
    4234         const int    numdof=NDOF2*NUMVERTICES;
    4235 
    4236         int        i,ig;
    4237         IssmDouble     Jelem=0;
    4238         IssmDouble     misfit,Jdet;
    4239         IssmDouble     vx,vy,vxobs,vyobs,weight;
    4240         IssmDouble     xyz_list[NUMVERTICES][3];
     4289        IssmDouble Jelem=0;
     4290        IssmDouble misfit,Jdet;
     4291        IssmDouble vx,vy,vxobs,vyobs,weight;
     4292        IssmDouble xyz_list[NUMVERTICES][3];
    42414293        GaussTria *gauss=NULL;
    42424294
     
    42564308        /* Start  looping on the number of gaussian points: */
    42574309        gauss=new GaussTria(2);
    4258         for (ig=gauss->begin();ig<gauss->end();ig++){
     4310        for(int ig=gauss->begin();ig<gauss->end();ig++){
    42594311
    42604312                gauss->GaussPoint(ig);
     
    42924344/*FUNCTION Tria::SurfaceRelVelMisfit {{{*/
    42934345IssmDouble Tria::SurfaceRelVelMisfit(bool process_units,int weight_index){
    4294         const int  numdof=2*NUMVERTICES;
    4295 
    4296         int        i,ig;
    4297         IssmDouble     Jelem=0;
    4298         IssmDouble     scalex=1,scaley=1;
    4299         IssmDouble     misfit,Jdet;
    4300         IssmDouble     epsvel=2.220446049250313e-16;
    4301         IssmDouble     meanvel=3.170979198376458e-05; /*1000 m/yr*/
    4302         IssmDouble     vx,vy,vxobs,vyobs,weight;
    4303         IssmDouble     xyz_list[NUMVERTICES][3];
     4346
     4347        IssmDouble  Jelem=0;
     4348        IssmDouble  scalex=1,scaley=1;
     4349        IssmDouble  misfit,Jdet;
     4350        IssmDouble  epsvel=2.220446049250313e-16;
     4351        IssmDouble  meanvel=3.170979198376458e-05; /*1000 m/yr*/
     4352        IssmDouble  vx,vy,vxobs,vyobs,weight;
     4353        IssmDouble  xyz_list[NUMVERTICES][3];
    43044354        GaussTria *gauss=NULL;
    43054355
     
    43194369        /* Start  looping on the number of gaussian points: */
    43204370        gauss=new GaussTria(4);
    4321         for (ig=gauss->begin();ig<gauss->end();ig++){
     4371        for(int ig=gauss->begin();ig<gauss->end();ig++){
    43224372
    43234373                gauss->GaussPoint(ig);
     
    43584408
    43594409        /* Intermediaries */
    4360         int        ig;
    4361         IssmDouble     Jelem = 0;
    4362         IssmDouble     weight;
    4363         IssmDouble     Jdet;
    4364         IssmDouble     xyz_list[NUMVERTICES][3];
    4365         IssmDouble     dp[NDOF2];
     4410        IssmDouble Jelem = 0;
     4411        IssmDouble weight;
     4412        IssmDouble Jdet;
     4413        IssmDouble xyz_list[NUMVERTICES][3];
     4414        IssmDouble dp[NDOF2];
    43664415        GaussTria *gauss = NULL;
    43674416
     
    43784427        /* Start looping on the number of gaussian points: */
    43794428        gauss=new GaussTria(2);
    4380         for (ig=gauss->begin();ig<gauss->end();ig++){
     4429        for(int ig=gauss->begin();ig<gauss->end();ig++){
    43814430
    43824431                gauss->GaussPoint(ig);
     
    44024451
    44034452        /* Intermediaries */
    4404         int         ig;
    44054453        IssmDouble  Jelem = 0;
    44064454        IssmDouble  weight;
     
    44254473        /* Start looping on the number of gaussian points: */
    44264474        gauss=new GaussTria(2);
    4427         for (ig=gauss->begin();ig<gauss->end();ig++){
     4475        for(int ig=gauss->begin();ig<gauss->end();ig++){
    44284476
    44294477                gauss->GaussPoint(ig);
     
    44544502
    44554503        /* Intermediaries */
    4456         int         ig;
    44574504        IssmDouble  Jelem = 0;
    44584505        IssmDouble  weight;
     
    44774524        /* Start looping on the number of gaussian points: */
    44784525        gauss=new GaussTria(2);
    4479         for (ig=gauss->begin();ig<gauss->end();ig++){
     4526        for(int ig=gauss->begin();ig<gauss->end();ig++){
    44804527
    44814528                gauss->GaussPoint(ig);
     
    45064553
    45074554        /*Intermediaries*/
    4508         int        i,ig;
    4509         IssmDouble     thickness,thicknessobs,weight;
    4510         IssmDouble     Jdet;
    4511         IssmDouble     Jelem = 0;
    4512         IssmDouble     xyz_list[NUMVERTICES][3];
     4555        IssmDouble thickness,thicknessobs,weight;
     4556        IssmDouble Jdet;
     4557        IssmDouble Jelem = 0;
     4558        IssmDouble xyz_list[NUMVERTICES][3];
    45134559        GaussTria *gauss = NULL;
    4514         IssmDouble     dH[2];
     4560        IssmDouble dH[2];
    45154561
    45164562        /*If on water, return 0: */
     
    45254571        /* Start  looping on the number of gaussian points: */
    45264572        gauss=new GaussTria(2);
    4527         for (ig=gauss->begin();ig<gauss->end();ig++){
     4573        for(int ig=gauss->begin();ig<gauss->end();ig++){
    45284574
    45294575                gauss->GaussPoint(ig);
     
    45544600
    45554601        /*Intermediaries */
    4556         int         i,ig,resp;
     4602        int         i,resp;
    45574603        IssmDouble  Jdet;
    45584604        IssmDouble  thickness,thicknessobs,weight;
     
    45814627        /* Start  looping on the number of gaussian points: */
    45824628        gauss=new GaussTria(2);
    4583         for(ig=gauss->begin();ig<gauss->end();ig++){
     4629        for(int ig=gauss->begin();ig<gauss->end();ig++){
    45844630
    45854631                gauss->GaussPoint(ig);
     
    46414687
    46424688        /*Intermediaries */
    4643         int        i,resp,ig;
     4689        int        i,resp;
    46444690        int       *responses=NULL;
    46454691        int        num_responses;
     
    46774723        /* Start  looping on the number of gaussian points: */
    46784724        gauss=new GaussTria(4);
    4679         for (ig=gauss->begin();ig<gauss->end();ig++){
     4725        for(int ig=gauss->begin();ig<gauss->end();ig++){
    46804726
    46814727                gauss->GaussPoint(ig);
     
    48234869
    48244870        /*Intermediaries */
    4825         int        i,resp,ig;
     4871        int        i,resp;
    48264872        int       *responses=NULL;
    48274873        int        num_responses;
     
    48594905        /* Start  looping on the number of gaussian points: */
    48604906        gauss=new GaussTria(4);
    4861         for (ig=gauss->begin();ig<gauss->end();ig++){
     4907        for(int ig=gauss->begin();ig<gauss->end();ig++){
    48624908
    48634909                gauss->GaussPoint(ig);
     
    50065052
    50075053        /* Intermediaries */
    5008         int        ig;
    5009         IssmDouble     Jelem = 0;
    5010         IssmDouble     weight;
    5011         IssmDouble     Jdet;
    5012         IssmDouble     xyz_list[NUMVERTICES][3];
    5013         IssmDouble     dp[NDOF2];
     5054        IssmDouble Jelem = 0;
     5055        IssmDouble weight;
     5056        IssmDouble Jdet;
     5057        IssmDouble xyz_list[NUMVERTICES][3];
     5058        IssmDouble dp[NDOF2];
    50145059        GaussTria *gauss = NULL;
    50155060
     
    50265071        /* Start looping on the number of gaussian points: */
    50275072        gauss=new GaussTria(2);
    5028         for (ig=gauss->begin();ig<gauss->end();ig++){
     5073        for(int ig=gauss->begin();ig<gauss->end();ig++){
    50295074
    50305075                gauss->GaussPoint(ig);
     
    50755120
    50765121        /*Intermediaries */
    5077         int        i,j,ig;
     5122        int        i,j;
    50785123        bool       incomplete_adjoint;
    5079         IssmDouble     xyz_list[NUMVERTICES][3];
    5080         IssmDouble     Jdet,thickness;
    5081         IssmDouble     eps1dotdphii,eps1dotdphij;
    5082         IssmDouble     eps2dotdphii,eps2dotdphij;
    5083         IssmDouble     mu_prime;
    5084         IssmDouble     epsilon[3];/* epsilon=[exx,eyy,exy];*/
    5085         IssmDouble     eps1[2],eps2[2];
    5086         IssmDouble     phi[NUMVERTICES];
    5087         IssmDouble     dphi[2][NUMVERTICES];
     5124        IssmDouble xyz_list[NUMVERTICES][3];
     5125        IssmDouble Jdet,thickness;
     5126        IssmDouble eps1dotdphii,eps1dotdphij;
     5127        IssmDouble eps2dotdphii,eps2dotdphij;
     5128        IssmDouble mu_prime;
     5129        IssmDouble epsilon[3];/* epsilon=[exx,eyy,exy];*/
     5130        IssmDouble eps1[2],eps2[2];
     5131        IssmDouble dphi[2][NUMVERTICES];
    50885132        GaussTria *gauss=NULL;
    50895133
     
    51015145        /* Start  looping on the number of gaussian points: */
    51025146        gauss=new GaussTria(2);
    5103         for (ig=gauss->begin();ig<gauss->end();ig++){
     5147        for(int ig=gauss->begin();ig<gauss->end();ig++){
    51045148
    51055149                gauss->GaussPoint(ig);
     
    52055249void  Tria::GetVectorFromControlInputs(Vector<IssmDouble>* vector,int control_enum,int control_index,const char* data){
    52065250
    5207         int doflist1[NUMVERTICES];
     5251        int vertexpidlist[NUMVERTICES];
    52085252        Input *input=NULL;
    52095253
     
    52125256
    52135257        /*Prepare index list*/
    5214         GradientIndexing(&doflist1[0],control_index);
     5258        GradientIndexing(&vertexpidlist[0],control_index);
    52155259
    52165260        /*Get input (either in element or material)*/
     
    52275271        }
    52285272
    5229         ((ControlInput*)input)->GetVectorFromInputs(vector,&doflist1[0],data);
     5273        ((ControlInput*)input)->GetVectorFromInputs(vector,&vertexpidlist[0],data);
    52305274}
    52315275/*}}}*/
     
    52345278
    52355279        IssmDouble  values[NUMVERTICES];
    5236         int     doflist1[NUMVERTICES];
     5280        int     vertexpidlist[NUMVERTICES];
    52375281        Input  *input     = NULL;
    52385282        Input  *new_input = NULL;
     
    52425286
    52435287        /*Prepare index list*/
    5244         GradientIndexing(&doflist1[0],control_index);
     5288        GradientIndexing(&vertexpidlist[0],control_index);
    52455289
    52465290        /*Get values on vertices*/
    52475291        for (int i=0;i<NUMVERTICES;i++){
    5248                 values[i]=vector[doflist1[i]];
     5292                values[i]=vector[vertexpidlist[i]];
    52495293        }
    52505294        new_input = new TriaP1Input(control_enum,values);
     
    52965340        /* compute VelocityFactor */
    52975341        VelocityFactor= n_man*CR*CR*rho_water*g/mu_water;
    5298        
     5342
    52995343        gauss=new GaussTria();
    53005344        for (int iv=0;iv<NUMVERTICES;iv++){
     
    53255369
    53265370        /*Constants*/
    5327         const int    numdof=NDOF1*NUMVERTICES;
     5371        const int  numdof=NDOF1*NUMVERTICES;
    53285372
    53295373        /*Intermediaries */
    5330         IssmDouble     diffusivity;
    5331         int        i,j,ig;
    5332         IssmDouble     Jdettria,DL_scalar,dt,h;
    5333         IssmDouble     vx,vy,vel,dvxdx,dvydy;
    5334         IssmDouble     dvx[2],dvy[2];
    5335         IssmDouble     v_gauss[2]={0.0};
    5336         IssmDouble     xyz_list[NUMVERTICES][3];
    5337         IssmDouble     L[NUMVERTICES];
    5338         IssmDouble     B[2][NUMVERTICES];
    5339         IssmDouble     Bprime[2][NUMVERTICES];
    5340         IssmDouble     K[2][2]                        ={0.0};
    5341         IssmDouble     KDL[2][2]                      ={0.0};
    5342         IssmDouble     DL[2][2]                        ={0.0};
    5343         IssmDouble     DLprime[2][2]                   ={0.0};
     5374        IssmDouble diffusivity;
     5375        IssmDouble Jdettria,DL_scalar,dt,h;
     5376        IssmDouble vx,vy,vel,dvxdx,dvydy;
     5377        IssmDouble dvx[2],dvy[2];
     5378        IssmDouble v_gauss[2]={0.0};
     5379        IssmDouble xyz_list[NUMVERTICES][3];
     5380        IssmDouble L[NUMVERTICES];
     5381        IssmDouble B[2][NUMVERTICES];
     5382        IssmDouble Bprime[2][NUMVERTICES];
     5383        IssmDouble K[2][2]                        ={0.0};
     5384        IssmDouble KDL[2][2]                      ={0.0};
     5385        IssmDouble DL[2][2]                        ={0.0};
     5386        IssmDouble DLprime[2][2]                   ={0.0};
    53445387        GaussTria *gauss=NULL;
    53455388
     
    53635406        /* Start  looping on the number of gaussian points: */
    53645407        gauss=new GaussTria(2);
    5365         for (ig=gauss->begin();ig<gauss->end();ig++){
     5408        for(int ig=gauss->begin();ig<gauss->end();ig++){
    53665409
    53675410                gauss->GaussPoint(ig);
     
    54335476
    54345477        /*Intermediaries */
    5435         int        i,j,ig;
    5436         IssmDouble     Jdettria,dt;
    5437         IssmDouble     basal_melting_g;
    5438         IssmDouble     old_watercolumn_g;
    5439         IssmDouble     xyz_list[NUMVERTICES][3];
    5440         IssmDouble     basis[numdof];
     5478        int        i,j;
     5479        IssmDouble Jdettria,dt;
     5480        IssmDouble basal_melting_g;
     5481        IssmDouble old_watercolumn_g;
     5482        IssmDouble xyz_list[NUMVERTICES][3];
     5483        IssmDouble basis[numdof];
    54415484        GaussTria* gauss=NULL;
    54425485
     
    54565499        /* Start  looping on the number of gaussian points: */
    54575500        gauss=new GaussTria(2);
    5458         for(ig=gauss->begin();ig<gauss->end();ig++){
     5501        for(int ig=gauss->begin();ig<gauss->end();ig++){
    54595502
    54605503                gauss->GaussPoint(ig);
     
    54695512                else  for(i=0;i<numdof;i++) pe->values[i]+=Jdettria*gauss->weight*basal_melting_g*basis[i];
    54705513        }
    5471                
     5514
    54725515        /*Clean up and return*/
    54735516        delete gauss;
     
    55415584/*FUNCTION Tria::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type);{{{*/
    55425585void  Tria::InputUpdateFromVectorDakota(IssmDouble* vector, int name, int type){
    5543        
     5586
    55445587        int i,j;
    55455588
     
    55565599                        /*Get values on the 3 vertices*/
    55575600                        for (i=0;i<3;i++){
    5558                                 values[i]=vector[this->nodes[i]->GetSidList()]; //careful, vector of values here is not parallel distributed, but serial distributed (from a serial Dakota core!)
     5601                                values[i]=vector[this->nodes[i]->GetVertexSid()]; //careful, vector of values here is not parallel distributed, but serial distributed (from a serial Dakota core!)
    55595602                        }
    55605603
     
    55675610                                        IssmDouble  surface[3];
    55685611                                        IssmDouble  bed[3];
    5569                                        
     5612
    55705613                                        /*retrieve inputs: */
    55715614                                        GetInputListOnVertices(&thickness_init[0],ThicknessEnum);
     
    56405683/*FUNCTION Tria::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type);{{{*/
    56415684void  Tria::InputUpdateFromMatrixDakota(IssmDouble* matrix, int nrows, int ncols, int name, int type){
    5642        
     5685
    56435686        int i,j,t;
    56445687        TransientInput* transientinput=NULL;
     
    56545697
    56555698                case VertexEnum:
    5656                        
     5699
    56575700                        /*Create transient input: */
    5658                                                
     5701
    56595702                        parameters->FindParam(&yts,ConstantsYtsEnum);
    56605703                        for(t=0;t<ncols;t++){ //ncols is the number of times
     
    56625705                                /*create input values: */
    56635706                                for(i=0;i<3;i++){
    5664                                         row=this->nodes[i]->GetSidList();
     5707                                        row=this->nodes[i]->GetVertexSid();
    56655708                                        values[i]=(IssmDouble)matrix[ncols*row+t];
    56665709                                }
     
    57075750        /*Intermediaries */
    57085751        int        stabilization;
    5709         int        i,j,ig,dim;
    5710         IssmDouble     Jdettria,vx,vy,dvxdx,dvydy,vel,h;
    5711         IssmDouble     dvx[2],dvy[2];
    5712         IssmDouble     xyz_list[NUMVERTICES][3];
    5713         IssmDouble     L[NUMVERTICES];
    5714         IssmDouble     B[2][NUMVERTICES];
    5715         IssmDouble     Bprime[2][NUMVERTICES];
    5716         IssmDouble     K[2][2]                          = {0.0};
    5717         IssmDouble     KDL[2][2]                        = {0.0};
    5718         IssmDouble     DL[2][2]                         = {0.0};
    5719         IssmDouble     DLprime[2][2]                    = {0.0};
    5720         IssmDouble     DL_scalar;
     5752        int        i,j,dim;
     5753        IssmDouble Jdettria,vx,vy,dvxdx,dvydy,vel,h;
     5754        IssmDouble dvx[2],dvy[2];
     5755        IssmDouble xyz_list[NUMVERTICES][3];
     5756        IssmDouble L[NUMVERTICES];
     5757        IssmDouble B[2][NUMVERTICES];
     5758        IssmDouble Bprime[2][NUMVERTICES];
     5759        IssmDouble K[2][2]                          = {0.0};
     5760        IssmDouble KDL[2][2]                        = {0.0};
     5761        IssmDouble DL[2][2]                         = {0.0};
     5762        IssmDouble DLprime[2][2]                    = {0.0};
     5763        IssmDouble DL_scalar;
    57215764        GaussTria *gauss                            = NULL;
    57225765
     
    57425785        /*Start looping on the number of gaussian points:*/
    57435786        gauss=new GaussTria(2);
    5744         for (ig=gauss->begin();ig<gauss->end();ig++){
     5787        for(int ig=gauss->begin();ig<gauss->end();ig++){
    57455788
    57465789                gauss->GaussPoint(ig);
     
    58165859
    58175860        /*Intermediaries*/
    5818         int        i,j,ig,dim;
    5819         IssmDouble     vx,vy,Jdettria;
    5820         IssmDouble     xyz_list[NUMVERTICES][3];
    5821         IssmDouble     B[2][NUMVERTICES];
    5822         IssmDouble     Bprime[2][NUMVERTICES];
    5823         IssmDouble     DL[2][2]={0.0};
    5824         IssmDouble     DL_scalar;
     5861        int        i,j,dim;
     5862        IssmDouble vx,vy,Jdettria;
     5863        IssmDouble xyz_list[NUMVERTICES][3];
     5864        IssmDouble B[2][NUMVERTICES];
     5865        IssmDouble Bprime[2][NUMVERTICES];
     5866        IssmDouble DL[2][2]={0.0};
     5867        IssmDouble DL_scalar;
    58255868        GaussTria  *gauss=NULL;
    58265869
     
    58365879        /*Start looping on the number of gaussian points:*/
    58375880        gauss=new GaussTria(2);
    5838         for (ig=gauss->begin();ig<gauss->end();ig++){
     5881        for(int ig=gauss->begin();ig<gauss->end();ig++){
    58395882
    58405883                gauss->GaussPoint(ig);
     
    58825925        /*Constants*/
    58835926        const int    numdof=NDOF1*NUMVERTICES;
    5884        
     5927
    58855928        /*Intermediaries */
    5886         int        i,j,ig;
    5887         IssmDouble     xyz_list[NUMVERTICES][3];
    5888         IssmDouble     dhdt_g,basal_melting_g,surface_mass_balance_g,Jdettria;
    5889         IssmDouble     L[NUMVERTICES];
     5929        int        i,j;
     5930        IssmDouble xyz_list[NUMVERTICES][3];
     5931        IssmDouble dhdt_g,basal_melting_g,surface_mass_balance_g,Jdettria;
     5932        IssmDouble L[NUMVERTICES];
    58905933        GaussTria* gauss=NULL;
    58915934
     
    58985941        Input* basal_melting_input=inputs->GetInput(BasalforcingsMeltingRateEnum);          _assert_(basal_melting_input);
    58995942        Input* dhdt_input=inputs->GetInput(BalancethicknessThickeningRateEnum);             _assert_(dhdt_input);
    5900        
     5943
    59015944        /* Start  looping on the number of gaussian points: */
    59025945        gauss=new GaussTria(2);
    5903         for(ig=gauss->begin();ig<gauss->end();ig++){
     5946        for(int ig=gauss->begin();ig<gauss->end();ig++){
    59045947
    59055948                gauss->GaussPoint(ig);
     
    59275970
    59285971        /*Intermediaries */
    5929         int        i,j,ig;
    5930         IssmDouble     xyz_list[NUMVERTICES][3];
    5931         IssmDouble     basal_melting_g,surface_mass_balance_g,dhdt_g,Jdettria;
    5932         IssmDouble     L[NUMVERTICES];
     5972        int        i,j;
     5973        IssmDouble xyz_list[NUMVERTICES][3];
     5974        IssmDouble basal_melting_g,surface_mass_balance_g,dhdt_g,Jdettria;
     5975        IssmDouble L[NUMVERTICES];
    59335976        GaussTria* gauss=NULL;
    59345977
     
    59445987        /* Start  looping on the number of gaussian points: */
    59455988        gauss=new GaussTria(2);
    5946         for(ig=gauss->begin();ig<gauss->end();ig++){
     5989        for(int ig=gauss->begin();ig<gauss->end();ig++){
    59475990
    59485991                gauss->GaussPoint(ig);
  • issm/trunk/src/c/classes/objects/Elements/Tria.h

    r13395 r13975  
    2929        public:
    3030
    31                 int  id;
    32                 int  sid;
    33 
    34                 Node   **nodes;    // 3 nodes
    35                 Material  *material;   // 1 material ice
    36                 Matpar  *matpar;   // 1 material parameter
    37                 int      horizontalneighborsids[3];
    38 
    39                 Parameters *parameters;   //pointer to solution parameters
    40                 Inputs     *inputs;
    41                 Results    *results;
     31                int          id;
     32                int          sid;
     33
     34                Node       **nodes;                       // 3 nodes
     35                Material    *material;                    // 1 material ice
     36                Matpar      *matpar;                      // 1 material parameter
     37                int          horizontalneighborsids[3];
     38
     39                Parameters  *parameters;                  //pointer to solution parameters
     40                Inputs      *inputs;
     41                Results     *results;
    4242
    4343                /*Tria constructors, destructors {{{*/
     
    4747                /*}}}*/
    4848                /*Object virtual functions definitions:{{{ */
    49                 void  Echo();
    50                 void  DeepEcho();
    51                 int   Id();
    52                 int   MyRank();
    53                 int   ObjectEnum();
    54                 Object* copy();
     49                void    Echo();
     50                void    DeepEcho();
     51                int     Id();
     52                int     ObjectEnum();
     53                Object *copy();
    5554                /*}}}*/
    5655                /*Update virtual functions resolution: {{{*/
     
    7776                void   Configure(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters);
    7877                void   SetCurrentConfiguration(Elements* elements,Loads* loads,DataSet* nodes,Materials* materials,Parameters* parameters);
     78                void   SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
    7979                void   CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,Vector<IssmDouble>* df);
    8080                void   CreatePVector(Vector<IssmDouble>* pf);
     
    8282                void   Delta18oParameterization(void);
    8383                int    GetNodeIndex(Node* node);
     84                int    GetNumberOfNodes(void);
     85                void   GetNodesSidList(int* sidlist);
    8486                int    Sid();
    8587                bool   IsOnBed();
     
    137139                #endif
    138140
    139 
    140141                #ifdef _HAVE_CONTROL_
    141142                IssmDouble DragCoefficientAbsGradient(bool process_units,int weight_index);
     
    190191                int            GetElementType(void);
    191192                void             GetDofList(int** pdoflist,int approximation_enum,int setenum);
    192                 void             GetDofList1(int* doflist);
    193                 void           GetSidList(int* sidlist);
     193                void             GetVertexPidList(int* doflist);
     194                void           GetVertexSidList(int* sidlist);
    194195                void           GetConnectivityList(int* connectivity);
    195196                void           GetInputListOnVertices(IssmDouble* pvalue,int enumtype);
     
    203204                void             SetClone(int* minranks);
    204205                void             SurfaceNormal(IssmDouble* surface_normal, IssmDouble xyz_list[3][3]);
    205                
     206
    206207                #ifdef _HAVE_DIAGNOSTIC_
    207208                ElementMatrix* CreateKMatrixDiagnosticMacAyeal(void);
  • issm/trunk/src/c/classes/objects/Elements/TriaHook.cpp

    r13395 r13975  
    5050        /*retrieve parameters: */
    5151        iomodel->Constant(&matpar_id,MeshNumberofelementsEnum); matpar_id++;
    52        
     52
    5353        this->numanalyses=in_numanalyses;
    5454        this->hnodes= new Hook*[in_numanalyses];
  • issm/trunk/src/c/classes/objects/Elements/TriaHook.h

    r13395 r13975  
    1717                Hook*  hmatpar; // 1 material parameter
    1818
    19 
    2019                /*FUNCTION constructors, destructors {{{*/
    2120                TriaHook();
     
    2726};
    2827
    29 
    3028#endif //ifndef _TRIAHOOK_H_
    31 
  • issm/trunk/src/c/classes/objects/Elements/TriaRef.cpp

    r13395 r13975  
    319319        y3=*(xyz_list+NUMNODES*2+1);
    320320
    321 
    322321        *(J+NDOF2*0+0)=0.5*(x2-x1);
    323322        *(J+NDOF2*1+0)=SQRT3/6.0*(2*x3-x1-x2);
  • issm/trunk/src/c/classes/objects/Elements/TriaRef.h

    r13395 r13975  
    33 * strain rate generation, etc ...
    44 */
    5 
    65
    76#ifndef _TRIAREF_H_
     
    1110
    1211class TriaRef{
    13        
    1412
    1513        public:
    1614                int* element_type_list; //P1CG, P1DG, MINI, P2...
    1715                int  element_type;
    18                
     16
    1917                TriaRef();
    2018                TriaRef(const int nummodels);
  • issm/trunk/src/c/classes/objects/ExternalResults/ExternalResult.h

    r13395 r13975  
    22 * \brief abstract class for ExternalResult object
    33 */
    4 
    54
    65#ifndef _EXTERNALRESULT_H_
     
    2322
    2423        public:
    25                
     24
    2625                virtual        ~ExternalResult(){};
    2726                /*Virtual functions:{{{*/
  • issm/trunk/src/c/classes/objects/ExternalResults/GenericExternalResult.h

    r13395 r13975  
    2020#include "../../../io/io.h"
    2121#include "../../../EnumDefinitions/EnumDefinitions.h"
     22#include "../../../classes/IssmComm.h"
    2223#include "./ExternalResult.h"
    2324/*}}}*/
     
    3435                int step;
    3536                IssmDouble time;
    36        
     37
    3738        public:
    3839                /*Diverse: must be in front, as it is used in what follows*/
     
    99100                        return -1;
    100101                } /*}}}*/
    101                 int MyRank(void){ /*{{{*/
    102                         extern int my_rank;
    103                         return my_rank;
    104                 } /*}}}*/
    105102                int ObjectEnum(void){ /*{{{*/
    106103                        _error_("template ObjectEnum not implemented for this ResultType\n");
     
    112109                /*GenericExternalResult management: */
    113110void WriteData(FILE* fid,bool io_gather){ /*{{{*/
    114                        
    115         extern  int my_rank;
     111
     112        int    my_rank;
    116113        int     type;
    117114        int     size;
    118115        IssmPDouble  passiveDouble;
    119        
     116
     117        /*recover my_rank:*/
     118        my_rank=IssmComm::GetRank();
     119
    120120        /*return if now on cpu 0: */
    121121        if(my_rank)return;
     
    205205template <> inline void GenericExternalResult<char*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
    206206
    207         extern  int my_rank;
     207        int    my_rank;
    208208        int     type;
    209209        int     length;
     210
     211        /*recover my_rank:*/
     212        my_rank=IssmComm::GetRank();
    210213
    211214        /*return if now on cpu 0: */
     
    235238        M=in_M;
    236239        N=in_N;
    237        
     240
    238241        step=in_step;
    239242        time=in_time;
     
    254257} /*}}}*/
    255258template <> inline void GenericExternalResult<IssmPDouble*>::Echo(void){ /*{{{*/
    256        
     259
     260        _printLine_("GenericExternalResult<IssmPDouble*>:");
     261        this->GenericEcho();
     262        _printLine_("   matrix size: " << this->M << "-" << this->N);
     263
     264} /*}}}*/
     265template <> inline void GenericExternalResult<IssmPDouble*>::DeepEcho(void){ /*{{{*/
     266
    257267        int i,j;
    258268
    259269        _printLine_("GenericExternalResult<IssmPDouble*>:");
    260270        this->GenericEcho();
    261         _printLine_("   matrix size: " << this->M << "-" << this->N);
    262 
    263 } /*}}}*/
    264 template <> inline void GenericExternalResult<IssmPDouble*>::DeepEcho(void){ /*{{{*/
    265        
    266         int i,j;
    267 
    268         _printLine_("GenericExternalResult<IssmPDouble*>:");
    269         this->GenericEcho();
    270        
     271
    271272        _printLine_("   matrix size: " << this->M << "-" << this->N);
    272273        for (i=0;i<this->M;i++){ 
     
    283284} /*}}}*/
    284285template <> inline void GenericExternalResult<IssmPDouble*>::WriteData(FILE* fid,bool io_gather){ /*{{{*/
    285        
    286         extern  int my_rank;
     286
     287        int    my_rank;
    287288        int     length;
    288289        int     type;
    289290        int     rows,cols;
    290291        char   *name    = NULL;
    291         extern  int my_rank;
    292292        IssmPDouble passiveDouble;
     293
     294        /*recover my_rank:*/
     295        my_rank=IssmComm::GetRank();
    293296
    294297        if(io_gather){
  • issm/trunk/src/c/classes/objects/Inputs/BoolInput.cpp

    r13395 r13975  
    2323}
    2424/*}}}*/
    25 /*FUNCTION BoolInput::BoolInput(IssmDouble* values){{{*/
    26 BoolInput::BoolInput(int in_enum_type,IssmBool in_value){
     25/*FUNCTION BoolInput::BoolInput(int in_enum_type,bool in_value){{{*/
     26BoolInput::BoolInput(int in_enum_type,bool in_value){
    2727
    2828        enum_type=in_enum_type;
     
    5353int    BoolInput::Id(void){ return -1; }
    5454/*}}}*/
    55 /*FUNCTION BoolInput::MyRank{{{*/
    56 int    BoolInput::MyRank(void){
    57         extern int my_rank;
    58         return my_rank;
    59 }
    60 /*}}}*/
    6155/*FUNCTION BoolInput::ObjectEnum{{{*/
    6256int BoolInput::ObjectEnum(void){
     
    6862/*FUNCTION BoolInput::copy{{{*/
    6963Object* BoolInput::copy() {
    70        
     64
    7165        return new BoolInput(this->enum_type,this->value);
    7266
    7367}
    7468/*}}}*/
    75        
     69
    7670/*BoolInput management*/
    7771/*FUNCTION BoolInput::InstanceEnum{{{*/
     
    9993/*FUNCTION BoolInput::SpawnResult{{{*/
    10094ElementResult* BoolInput::SpawnResult(int step, IssmDouble time){
    101        
     95
    10296        return new BoolElementResult(this->enum_type,this->value,step,time);
    10397
  • issm/trunk/src/c/classes/objects/Inputs/BoolInput.h

    r13395 r13975  
    22 *  \brief: header file for triavertexinput object
    33 */
    4 
    54
    65#ifndef _BOOLINPUT_H_
     
    1817        public:
    1918                /*just hold 3 values for 3 vertices: */
    20                 int    enum_type;
    21                 IssmBool value;
     19                int  enum_type;
     20                bool value;
    2221
    2322                /*BoolInput constructors, destructors: {{{*/
    2423                BoolInput();
    25                 BoolInput(int enum_type,IssmBool value);
     24                BoolInput(int enum_type,bool value);
    2625                ~BoolInput();
    2726                /*}}}*/
    2827                /*Object virtual functions definitions:{{{ */
    29                 void  Echo();
    30                 void  DeepEcho();
    31                 int   Id();
    32                 int   MyRank();
    33                 int   ObjectEnum();
    34                 Object* copy();
     28                void    Echo();
     29                void    DeepEcho();
     30                int     Id();
     31                int     ObjectEnum();
     32                Object *copy();
    3533                /*}}}*/
    3634                /*BoolInput management: {{{*/
  • issm/trunk/src/c/classes/objects/Inputs/ControlInput.cpp

    r13395 r13975  
    8484int    ControlInput::Id(void){ return -1; }
    8585/*}}}*/
    86 /*FUNCTION ControlInput::MyRank{{{*/
    87 int    ControlInput::MyRank(void){
    88         extern int my_rank;
    89         return my_rank;
    90 }
    91 /*}}}*/
    9286/*FUNCTION ControlInput::ObjectEnum{{{*/
    9387int ControlInput::ObjectEnum(void){
     
    9993/*FUNCTION ControlInput::copy{{{*/
    10094Object* ControlInput::copy() {
    101        
     95
    10296        ControlInput* output=NULL;
    10397
     
    106100        output->control_id=this->control_id;
    107101
    108         if(values)      output->values=(Input*)this->values->copy();
    109         if(savedvalues) output->savedvalues=(Input*)this->savedvalues->copy();
    110         if(minvalues)   output->minvalues=(Input*)this->minvalues->copy();
    111         if(maxvalues)   output->maxvalues=(Input*)this->maxvalues->copy();
    112         if(gradient)    output->gradient=(Input*)this->gradient->copy();
     102        if(values)      output->values      = dynamic_cast<Input*>(this->values->copy());
     103        if(savedvalues) output->savedvalues = dynamic_cast<Input*>(this->savedvalues->copy());
     104        if(minvalues)   output->minvalues   = dynamic_cast<Input*>(this->minvalues->copy());
     105        if(maxvalues)   output->maxvalues   = dynamic_cast<Input*>(this->maxvalues->copy());
     106        if(gradient)    output->gradient    = dynamic_cast<Input*>(this->gradient->copy());
    113107
    114108        return output;
    115109}
    116110/*}}}*/
    117        
     111
    118112/*ControlInput management*/
    119113/*FUNCTION ControlInput::InstanceEnum{{{*/
     
    261255
    262256        if(savedvalues) delete this->savedvalues;
    263         this->savedvalues=(Input*)this->values->copy();
     257        this->savedvalues=dynamic_cast<Input*>(this->values->copy());
    264258}/*}}}*/
    265259/*FUNCTION ControlInput::UpdateValue{{{*/
     
    269263
    270264        if(values) delete this->values;
    271         this->values=(Input*)this->savedvalues->copy();
     265        this->values=dynamic_cast<Input*>(this->savedvalues->copy());
    272266        this->values->AXPY(gradient,scalar);
    273267}/*}}}*/
  • issm/trunk/src/c/classes/objects/Inputs/ControlInput.h

    r13395 r13975  
    22 *  \brief: header file for triavertexinput object
    33 */
    4 
    54
    65#ifndef _CONTROLINPUT_H_
     
    3433                void  DeepEcho();
    3534                int   Id();
    36                 int   MyRank();
    3735                int   ObjectEnum();
    3836                Object* copy();
  • issm/trunk/src/c/classes/objects/Inputs/DatasetInput.cpp

    r13395 r13975  
    5555int    DatasetInput::Id(void){ return -1; }
    5656/*}}}*/
    57 /*FUNCTION DatasetInput::MyRank{{{*/
    58 int    DatasetInput::MyRank(void){
    59         extern int my_rank;
    60         return my_rank;
    61 }
    62 /*}}}*/
    6357/*FUNCTION DatasetInput::ObjectEnum{{{*/
    6458int DatasetInput::ObjectEnum(void){
     
    7064/*FUNCTION DatasetInput::copy{{{*/
    7165Object* DatasetInput::copy() {
    72        
     66
    7367        DatasetInput* output=NULL;
    7468
     
    8983        outinput=new DatasetInput();
    9084        outinput->enum_type=this->enum_type;
    91         outinput->inputs=(Inputs*)this->inputs->SpawnTriaInputs(indices);
     85        outinput->inputs=dynamic_cast<Inputs*>(this->inputs->SpawnTriaInputs(indices));
    9286
    9387        /*Assign output*/
     
    9589}
    9690/*}}}*/
    97        
     91
    9892/*DatasetInput management*/
    9993/*FUNCTION DatasetInput::InstanceEnum{{{*/
     
    116110        /*Get requested input within dataset*/
    117111        if(index<0 || index > inputs->Size()-1) _error_("index requested (" << index << ") exceeds dataset size (" << inputs->Size() << ")");
    118         Input* input=(Input*)this->inputs->GetObjectByOffset(index);
    119        
     112        Input* input=dynamic_cast<Input*>(this->inputs->GetObjectByOffset(index));
     113
    120114        input->GetInputValue(pvalue,gauss);
    121115}
  • issm/trunk/src/c/classes/objects/Inputs/DatasetInput.h

    r13395 r13975  
    22 *  \brief: header file for datasetinput object
    33 */
    4 
    54
    65#ifndef _DATASETINPUT_H_
     
    1716
    1817        public:
    19                 int    enum_type;
    20 
    21                 Inputs*     inputs;
     18                int     enum_type;
     19                Inputs *inputs;
    2220
    2321                /*DatasetInput constructors, destructors: {{{*/
     
    3028                void  DeepEcho();
    3129                int   Id();
    32                 int   MyRank();
    3330                int   ObjectEnum();
    3431                Object* copy();
  • issm/trunk/src/c/classes/objects/Inputs/DoubleInput.cpp

    r13395 r13975  
    5353int    DoubleInput::Id(void){ return -1; }
    5454/*}}}*/
    55 /*FUNCTION DoubleInput::MyRank{{{*/
    56 int    DoubleInput::MyRank(void){
    57         extern int my_rank;
    58         return my_rank;
    59 }
    60 /*}}}*/
    6155/*FUNCTION DoubleInput::ObjectEnum{{{*/
    6256int DoubleInput::ObjectEnum(void){
     
    6862/*FUNCTION DoubleInput::copy{{{*/
    6963Object* DoubleInput::copy() {
    70        
     64
    7165        return new DoubleInput(this->enum_type,this->value);
    7266
    7367}
    7468/*}}}*/
    75        
     69
    7670/*DoubleInput management*/
    7771/*FUNCTION DoubleInput::InstanceEnum{{{*/
  • issm/trunk/src/c/classes/objects/Inputs/DoubleInput.h

    r13395 r13975  
    22 *  \brief: header file for triavertexinput object
    33 */
    4 
    54
    65#ifndef _DOUBLEINPUT_H_
     
    2928                void  DeepEcho();
    3029                int   Id();
    31                 int   MyRank();
    3230                int   ObjectEnum();
    3331                Object* copy();
  • issm/trunk/src/c/classes/objects/Inputs/Input.h

    r13395 r13975  
    22 * \brief abstract class for Input object
    33 */
    4 
    54
    65#ifndef _INPUT_H_
     
    1918
    2019        public:
    21                
     20
    2221                virtual        ~Input(){};
    2322
     
    6059                virtual void   GetVectorFromInputs(Vector<IssmDouble>* vector,int* doflist)=0;
    6160                virtual void   GetValuesPtr(IssmDouble** pvalues,int* pnum_values)=0;
    62                
     61
    6362                virtual Input* SpawnTriaInput(int* indices)=0;
    6463                virtual Input* PointwiseDivide(Input* inputB)=0;
  • issm/trunk/src/c/classes/objects/Inputs/IntInput.cpp

    r13395 r13975  
    4848int    IntInput::Id(void){ return -1; }
    4949/*}}}*/
    50 /*FUNCTION IntInput::MyRank{{{*/
    51 int    IntInput::MyRank(void){
    52         extern int my_rank;
    53         return my_rank;
    54 }
    55 /*}}}*/
    5650/*FUNCTION IntInput::ObjectEnum{{{*/
    5751int IntInput::ObjectEnum(void){
     
    6357/*FUNCTION IntInput::copy{{{*/
    6458Object* IntInput::copy() {
    65        
     59
    6660        return new IntInput(this->enum_type,this->value);
    6761
     
    9892/*FUNCTION IntInput::SpawnResult{{{*/
    9993ElementResult* IntInput::SpawnResult(int step, IssmDouble time){
    100        
     94
    10195        _error_("not supported yet!");
    10296
  • issm/trunk/src/c/classes/objects/Inputs/IntInput.h

    r13395 r13975  
    22 *  \brief: header file for triavertexinput object
    33 */
    4 
    54
    65#ifndef _INTINPUT_H_
     
    3029                void  DeepEcho();
    3130                int   Id();
    32                 int   MyRank();
    3331                int   ObjectEnum();
    3432                Object* copy();
  • issm/trunk/src/c/classes/objects/Inputs/PentaP1Input.cpp

    r13395 r13975  
    6464int    PentaP1Input::Id(void){ return -1; }
    6565/*}}}*/
    66 /*FUNCTION PentaP1Input::MyRank{{{*/
    67 int    PentaP1Input::MyRank(void){
    68         extern int my_rank;
    69         return my_rank;
    70 }
    71 /*}}}*/
    7266/*FUNCTION PentaP1Input::ObjectEnum{{{*/
    7367int PentaP1Input::ObjectEnum(void){
     
    7771}
    7872/*}}}*/
    79        
     73
    8074/*PentaP1Input management*/
    8175/*FUNCTION PentaP1Input::copy{{{*/
    8276Object* PentaP1Input::copy() {
    83        
     77
    8478        return new PentaP1Input(this->enum_type,this->values);
    8579
     
    363357/*FUNCTION PentaP1Input::ConstrainMin{{{*/
    364358void PentaP1Input::ConstrainMin(IssmDouble minimum){
    365        
     359
    366360        int i;
    367361        const int numnodes=6;
     
    431425/*FUNCTION PentaP1Input::Scale{{{*/
    432426void PentaP1Input::Scale(IssmDouble scale_factor){
    433        
     427
    434428        int i;
    435429        const int numnodes=6;
     
    470464        int i;
    471465        const int numnodes=6;
    472                
     466
    473467        if(!xIsNan<IssmDouble>(cm_min)) for(i=0;i<numnodes;i++)if (this->values[i]<cm_min)this->values[i]=cm_min;
    474468        if(!xIsNan<IssmDouble>(cm_max)) for(i=0;i<numnodes;i++)if (this->values[i]>cm_max)this->values[i]=cm_max;
     
    522516
    523517        /*Intermediaries*/
    524         int               i;
    525         PentaP1Input *xinputB     = NULL;
    526         int               B_numvalues;
    527         const int         numnodes    = 6;
    528         IssmDouble            AdotBvalues[numnodes];
     518        PentaP1Input *xinputB  = NULL;
     519        const int     numnodes = 6;
     520        IssmDouble    AdotBvalues[numnodes];
    529521
    530522        /*Check that inputB is of the same type*/
     
    533525
    534526        /*Create point wise sum*/
    535         for(i=0;i<numnodes;i++){
     527        for(int i=0;i<numnodes;i++){
    536528                _assert_(xinputB->values[i]!=0);
    537529                AdotBvalues[i]=this->values[i]/xinputB->values[i];
     
    555547        int               i;
    556548        PentaP1Input *xinputB     = NULL;
    557         int               B_numvalues;
    558549        const int         numnodes    = 6;
    559550        IssmDouble            minvalues[numnodes];
     
    586577        int               i;
    587578        PentaP1Input *xinputB     = NULL;
    588         int               B_numvalues;
    589579        const int         numnodes    = 6;
    590580        IssmDouble            maxvalues[numnodes];
  • issm/trunk/src/c/classes/objects/Inputs/PentaP1Input.h

    r13395 r13975  
    22 *  \brief: header file for PentaP1Input object
    33 */
    4 
    54
    65#ifndef _PENTAP1INPUT_H_
     
    1817        public:
    1918                /*just hold 6 values for 6 vertices: */
    20                 int    enum_type;
     19                int        enum_type;
    2120                IssmDouble values[6];
    2221
     
    2726                /*}}}*/
    2827                /*Object virtual functions definitions:{{{ */
    29                 void  Echo();
    30                 void  DeepEcho();
    31                 int   Id();
    32                 int   MyRank();
    33                 int   ObjectEnum();
    34                 Object* copy();
     28                void    Echo();
     29                void    DeepEcho();
     30                int     Id();
     31                int     ObjectEnum();
     32                Object *copy();
    3533                /*}}}*/
    3634                /*PentaP1Input management: {{{*/
  • issm/trunk/src/c/classes/objects/Inputs/TransientInput.cpp

    r13395 r13975  
    7979int    TransientInput::Id(void){ return -1; }
    8080/*}}}*/
    81 /*FUNCTION TransientInput::MyRank{{{*/
    82 int    TransientInput::MyRank(void){
    83         extern int my_rank;
    84         return my_rank;
    85 }
    86 /*}}}*/
    8781/*FUNCTION TransientInput::ObjectEnum{{{*/
    8882int TransientInput::ObjectEnum(void){
     
    109103}
    110104/*}}}*/
    111        
     105
    112106/*TransientInput management*/
    113107/*FUNCTION TransientInput::InstanceEnum{{{*/
     
    222216        /*Retrieve interpolated values for this time step: */
    223217        Input* input=GetTimeInput(time);
    224                    
     218
    225219        /*Call input function*/
    226220        input->GetInputDerivativeValue(p,xyz_list,gauss);
     
    237231/*FUNCTION TransientInput::GetInputAverage{{{*/
    238232void TransientInput::GetInputAverage(IssmDouble* pvalue){
    239        
     233
    240234        IssmDouble time;
    241235
     
    248242        /*Call input function*/
    249243        input->GetInputAverage(pvalue);
    250                            
     244
    251245        delete input;
    252246
     
    302296   /*Retrieve interpolated values for this time step: */
    303297        Input* input=GetTimeInput(time);
    304                    
     298
    305299        /*Call input function*/
    306300        input->SquareMin(psquaremin,process_units,parameters);
    307                            
     301
    308302        delete input;
    309303
     
    324318        /*Call input function*/
    325319        infnorm=input->InfinityNorm();
    326                            
     320
    327321        /*Clean-up and return*/
    328322        delete input;
     
    341335   /*Retrieve interpolated values for this time step: */
    342336        Input* input=GetTimeInput(time);
    343                    
     337
    344338        /*Call input function*/
    345339        max=input->Max();
    346                            
     340
    347341        delete input;
    348342
     
    406400        /*Call input function*/
    407401        minabs=input->MinAbs();
    408                            
     402
    409403        /*Clean-up and return*/
    410404        delete input;
     
    422416        /*Retrieve interpolated values for this time step: */
    423417        Input* input=GetTimeInput(time);
    424                    
     418
    425419        /*Call input function*/
    426420        input->GetVectorFromInputs(vector,doflist);
    427                            
     421
    428422        delete input;
    429423
     
    432426Input* TransientInput::GetTimeInput(IssmDouble intime){
    433427
    434         int     i,j;
    435         IssmDouble  deltat;
    436         IssmDouble  alpha1,alpha2;
    437         bool    found=false;
    438         Input*  input=NULL;
    439         Input*  input1=NULL;
    440         Input*  input2=NULL;
    441 
    442         /*Ok, we have the time, go through the timesteps, and figure out which interval we
     428        IssmDouble deltat;
     429        IssmDouble alpha1,alpha2;
     430        int        found;
     431        int        offset;
     432
     433        Input *input  = NULL;
     434        Input *input1 = NULL;
     435        Input *input2 = NULL;
     436
     437        /*go through the timesteps, and figure out which interval we
    443438         *fall within. Then interpolate the values on this interval: */
    444         if(intime<this->timesteps[0]){
     439        found=binary_search(&offset,intime,this->timesteps,this->numtimesteps);
     440        if(!found) _error_("Input not found (is TransientInput sorted ?)");
     441
     442        if (offset==-1){
    445443                /*get values for the first time: */
     444                _assert_(intime<this->timesteps[0]);
    446445                input=(Input*)((Input*)this->inputs->GetObjectByOffset(0))->copy();
    447                 found=true;
    448         }
    449         else if(intime>this->timesteps[this->numtimesteps-1]){
     446        }
     447        else if(offset==(this->numtimesteps-1)){
    450448                /*get values for the last time: */
    451                 input=(Input*)((Input*)this->inputs->GetObjectByOffset(numtimesteps-1))->copy();
    452                 found=true;
     449                _assert_(intime>=this->timesteps[offset]);
     450                input=(Input*)((Input*)this->inputs->GetObjectByOffset(offset))->copy();
    453451        }
    454452        else{
    455                 /*Find which interval we fall within: */
    456                 for(i=0;i<this->numtimesteps;i++){
    457                         if(intime==this->timesteps[i]){
    458                                 /*We are right on one step time: */
    459                                 input=(Input*)((Input*)this->inputs->GetObjectByOffset(i))->copy();
    460                                 found=true;
    461                                 break; //we are done with the time interpolation.
    462                         }
    463                         else{
    464                                 if(this->timesteps[i]<intime && intime<this->timesteps[i+1]){
    465                                         /*ok, we have the interval ]i:i+1[. Interpolate linearly for now: */
    466                                         deltat=this->timesteps[i+1]-this->timesteps[i];
    467                                         alpha2=(intime-this->timesteps[i])/deltat;
    468                                         alpha1=(1.0-alpha2);
    469 
    470                                         input1=(Input*)this->inputs->GetObjectByOffset(i);
    471                                         input2=(Input*)this->inputs->GetObjectByOffset(i+1);
    472 
    473                                         input=(Input*)input1->copy();
    474                                         input->Scale(alpha1);
    475                                         input->AXPY(input2,alpha2);
    476 
    477                                         found=true;
    478                                         break;
    479                                 }
    480                                 else continue; //keep looking on the next interval
    481                         }
    482                 }
    483         }
    484         if(!found)_error_("did not find time interval on which to interpolate forcing values!");
     453                /*get values between two times [offset:offset+1[, Interpolate linearly*/
     454                _assert_(intime>=this->timesteps[offset] && intime<this->timesteps[offset+1]);
     455                deltat=this->timesteps[offset+1]-this->timesteps[offset];
     456                alpha2=(intime-this->timesteps[offset])/deltat;
     457                alpha1=(1.0-alpha2);
     458
     459                input1=(Input*)this->inputs->GetObjectByOffset(offset);
     460                input2=(Input*)this->inputs->GetObjectByOffset(offset+1);
     461
     462                input=(Input*)input1->copy();
     463                input->Scale(alpha1);
     464                input->AXPY(input2,alpha2);
     465        }
    485466
    486467        /*Assign output pointer*/
  • issm/trunk/src/c/classes/objects/Inputs/TransientInput.h

    r13395 r13975  
    22 *  \brief: header file for transientinput object
    33 */
    4 
    54
    65#ifndef _TRANSIENTINPUT_H_
     
    1716
    1817        public:
    19                 int     enum_type;
    20                 int     numtimesteps;
    21                 Inputs* inputs;
    22                 IssmDouble* timesteps;
    23                 Parameters* parameters; //to find current time.
     18                int         enum_type;
     19                int         numtimesteps;
     20                Inputs     *inputs;
     21                IssmDouble *timesteps;
     22                Parameters *parameters;    //to find current time.
    2423
    2524                /*TransientInput constructors, destructors: {{{*/
     
    3332                void  DeepEcho();
    3433                int   Id();
    35                 int   MyRank();
    3634                int   ObjectEnum();
    3735                Object* copy();
  • issm/trunk/src/c/classes/objects/Inputs/TriaP1Input.cpp

    r13395 r13975  
    6464int    TriaP1Input::Id(void){ return -1; }
    6565/*}}}*/
    66 /*FUNCTION TriaP1Input::MyRank{{{*/
    67 int    TriaP1Input::MyRank(void){
    68         extern int my_rank;
    69         return my_rank;
    70 }
    71 /*}}}*/
    7266/*FUNCTION TriaP1Input::ObjectEnum{{{*/
    7367int TriaP1Input::ObjectEnum(void){
     
    7973/*FUNCTION TriaP1Input::copy{{{*/
    8074Object* TriaP1Input::copy() {
    81        
     75
    8276        return new TriaP1Input(this->enum_type,this->values);
    8377
    8478}
    8579/*}}}*/
    86        
     80
    8781/*TriaP1Input management*/
    8882/*FUNCTION TriaP1Input::InstanceEnum{{{*/
     
    214208/*FUNCTION TriaP1Input::ContrainMin{{{*/
    215209void TriaP1Input::ConstrainMin(IssmDouble minimum){
    216        
     210
    217211        int i;
    218212        const int numnodes=3;
     
    282276/*FUNCTION TriaP1Input::Scale{{{*/
    283277void TriaP1Input::Scale(IssmDouble scale_factor){
    284        
     278
    285279        int i;
    286280        const int numnodes=3;
     
    333327        int i;
    334328        const int numnodes=3;
    335                
     329
    336330        if(!xIsNan<IssmDouble>(cm_min)) for(i=0;i<numnodes;i++)if (this->values[i]<cm_min)this->values[i]=cm_min;
    337331        if(!xIsNan<IssmDouble>(cm_max)) for(i=0;i<numnodes;i++)if (this->values[i]>cm_max)this->values[i]=cm_max;
     
    361355
    362356        /*Intermediaries*/
    363         int               i;
    364         TriaP1Input *xinputB     = NULL;
    365         int               B_numvalues;
    366         const int         numnodes    = 3;
    367         IssmDouble            minvalues[numnodes];
     357        int          i;
     358        TriaP1Input *xinputB  = NULL;
     359        const int    numnodes = 3;
     360        IssmDouble   minvalues[numnodes];
    368361
    369362        /*Check that inputB is of the same type*/
     
    394387        int               i;
    395388        TriaP1Input *xinputB     = NULL;
    396         int               B_numvalues;
    397389        const int         numnodes    = 3;
    398390        IssmDouble            maxvalues[numnodes];
  • issm/trunk/src/c/classes/objects/Inputs/TriaP1Input.h

    r13395 r13975  
    22 *  \brief: header file for TriaP1Input object
    33 */
    4 
    54
    65#ifndef _TRIAP1INPUT_H_
     
    1817        public:
    1918                /*just hold 3 values for 3 vertices: */
    20                 int    enum_type;
     19                int        enum_type;
    2120                IssmDouble values[3];
    2221
     
    2726                /*}}}*/
    2827                /*Object virtual functions definitions:{{{ */
    29                 void  Echo();
    30                 void  DeepEcho();
    31                 int   Id();
    32                 int   MyRank();
    33                 int   ObjectEnum();
    34                 Object* copy();
     28                void    Echo();
     29                void    DeepEcho();
     30                int     Id();
     31                int     ObjectEnum();
     32                Object *copy();
    3533                /*}}}*/
    3634                /*TriaP1Input management: {{{*/
  • issm/trunk/src/c/classes/objects/KML/KMLFileReadUtils.cpp

    r13395 r13975  
    545545                                          FILE* fid){
    546546
    547         int     i=-1,j;
     547        int     i=-1;
    548548        char*   kstr;
    549549        char*   ktok;
  • issm/trunk/src/c/classes/objects/KML/KMLFileReadUtils.h

    r13395 r13975  
    5555
    5656#endif  /* _KMLFILEREADUTILS_H */
    57 
  • issm/trunk/src/c/classes/objects/KML/KML_Attribute.h

    r13395 r13975  
    3131                virtual void  DeepEcho(const char* indent);
    3232                int   Id(){_error_("Not implemented yet.");};
    33                 int   MyRank(){_error_("Not implemented yet.");};
    34                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    35                 int   MarshallSize(){_error_("Not implemented yet.");};
    36                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    3733                int   ObjectEnum(){_error_("Not implemented yet.");};
    3834                Object* copy(){_error_("Not implemented yet.");};
     
    4844};
    4945#endif  /* _KML_ATTRIBUTE_H */
    50 
  • issm/trunk/src/c/classes/objects/KML/KML_ColorStyle.h

    r13395 r13975  
    3636                void  Read(FILE* fid,char* kstr);
    3737                int   Id(){_error_("Not implemented yet.");};
    38                 int   MyRank(){_error_("Not implemented yet.");};
    39                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    40                 int   MarshallSize(){_error_("Not implemented yet.");};
    4138                void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    4239                int   ObjectEnum(){_error_("Not implemented yet.");};
     
    4643};
    4744#endif  /* _KML_COLORSTYLE_H */
    48 
  • issm/trunk/src/c/classes/objects/KML/KML_Comment.h

    r13395 r13975  
    3131                virtual void  DeepEcho(const char* indent);
    3232                int   Id(){_error_("Not implemented yet.");};
    33                 int   MyRank(){_error_("Not implemented yet.");};
    34                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    35                 int   MarshallSize(){_error_("Not implemented yet.");};
    36                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    3733                int   ObjectEnum(){_error_("Not implemented yet.");};
    3834                Object* copy(){_error_("Not implemented yet.");};
     
    4844};
    4945#endif  /* _KML_COMMENT_H */
    50 
  • issm/trunk/src/c/classes/objects/KML/KML_Container.h

    r13395 r13975  
    3434                void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
    3535                int   Id(){_error_("Not implemented yet.");};
    36                 int   MyRank(){_error_("Not implemented yet.");};
    37                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    38                 int   MarshallSize(){_error_("Not implemented yet.");};
    39                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    4036                int   ObjectEnum(){_error_("Not implemented yet.");};
    4137                Object* copy(){_error_("Not implemented yet.");};
     
    4440};
    4541#endif  /* _KML_CONTAINER_H */
    46 
  • issm/trunk/src/c/classes/objects/KML/KML_Document.cpp

    r13395 r13975  
    125125}
    126126/*}}}*/
    127 
  • issm/trunk/src/c/classes/objects/KML/KML_Document.h

    r13395 r13975  
    3131                void  Read(FILE* fid,char* kstr);
    3232                int   Id(){_error_("Not implemented yet.");};
    33                 int   MyRank(){_error_("Not implemented yet.");};
    34                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    35                 int   MarshallSize(){_error_("Not implemented yet.");};
    36                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    3733                int   ObjectEnum(){_error_("Not implemented yet.");};
    3834                Object* copy(){_error_("Not implemented yet.");};
     
    4137};
    4238#endif  /* _KML_DOCUMENT_H */
    43 
  • issm/trunk/src/c/classes/objects/KML/KML_Feature.h

    r13395 r13975  
    4545                void  Read(FILE* fid,char* kstr);
    4646                int   Id(){_error_("Not implemented yet.");};
    47                 int   MyRank(){_error_("Not implemented yet.");};
    48                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    49                 int   MarshallSize(){_error_("Not implemented yet.");};
    50                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    5147                int   ObjectEnum(){_error_("Not implemented yet.");};
    5248                Object* copy(){_error_("Not implemented yet.");};
     
    5551};
    5652#endif  /* _KML_FEATURE_H */
    57 
  • issm/trunk/src/c/classes/objects/KML/KML_File.cpp

    r13395 r13975  
    9090        int          ncom=0;
    9191        char**       pcom=NULL;
    92         KML_Object*  kobj;
    9392
    9493/*  get object attributes and check for solo tag  */
  • issm/trunk/src/c/classes/objects/KML/KML_File.h

    r13395 r13975  
    3232                void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
    3333                int   Id(){_error_("Not implemented yet.");};
    34                 int   MyRank(){_error_("Not implemented yet.");};
    35                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    36                 int   MarshallSize(){_error_("Not implemented yet.");};
    37                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    3834                int   ObjectEnum(){_error_("Not implemented yet.");};
    3935                Object* copy(){_error_("Not implemented yet.");};
     
    4238};
    4339#endif  /* _KML_FILE_H */
    44 
  • issm/trunk/src/c/classes/objects/KML/KML_Folder.h

    r13395 r13975  
    3131                void  Read(FILE* fid,char* kstr);
    3232                int   Id(){_error_("Not implemented yet.");};
    33                 int   MyRank(){_error_("Not implemented yet.");};
    34                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    35                 int   MarshallSize(){_error_("Not implemented yet.");};
    36                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    3733                int   ObjectEnum(){_error_("Not implemented yet.");};
    3834                Object* copy(){_error_("Not implemented yet.");};
     
    4137};
    4238#endif  /* _KML_FOLDER_H */
    43 
  • issm/trunk/src/c/classes/objects/KML/KML_Geometry.h

    r13395 r13975  
    3030                void  Read(FILE* fid,char* kstr);
    3131                int   Id(){_error_("Not implemented yet.");};
    32                 int   MyRank(){_error_("Not implemented yet.");};
    33                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    34                 int   MarshallSize(){_error_("Not implemented yet.");};
    35                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    3632                int   ObjectEnum(){_error_("Not implemented yet.");};
    3733                Object* copy(){_error_("Not implemented yet.");};
     
    4036};
    4137#endif  /* _KML_GEOMETRY_H */
    42 
  • issm/trunk/src/c/classes/objects/KML/KML_GroundOverlay.h

    r13395 r13975  
    3737                void  Read(FILE* fid,char* kstr);
    3838                int   Id(){_error_("Not implemented yet.");};
    39                 int   MyRank(){_error_("Not implemented yet.");};
    40                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    41                 int   MarshallSize(){_error_("Not implemented yet.");};
    42                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    4339                int   ObjectEnum(){_error_("Not implemented yet.");};
    4440                Object* copy(){_error_("Not implemented yet.");};
     
    4743};
    4844#endif  /* _KML_GROUNDOVERLAY_H */
    49 
  • issm/trunk/src/c/classes/objects/KML/KML_Icon.h

    r13395 r13975  
    4545                void  Read(FILE* fid,char* kstr);
    4646                int   Id(){_error_("Not implemented yet.");};
    47                 int   MyRank(){_error_("Not implemented yet.");};
    48                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    49                 int   MarshallSize(){_error_("Not implemented yet.");};
    50                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    5147                int   ObjectEnum(){_error_("Not implemented yet.");};
    5248                Object* copy(){_error_("Not implemented yet.");};
     
    5551};
    5652#endif  /* _KML_ICON_H */
    57 
  • issm/trunk/src/c/classes/objects/KML/KML_LatLonBox.cpp

    r13395 r13975  
    4343/*FUNCTION KML_LatLonBox::Echo {{{*/
    4444void  KML_LatLonBox::Echo(){
    45 
    4645
    4746        _printLine_("KML_LatLonBox:");
  • issm/trunk/src/c/classes/objects/KML/KML_LatLonBox.h

    r13395 r13975  
    3636                void  Read(FILE* fid,char* kstr);
    3737                int   Id(){_error_("Not implemented yet.");};
    38                 int   MyRank(){_error_("Not implemented yet.");};
    39                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    40                 int   MarshallSize(){_error_("Not implemented yet.");};
    41                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    4238                int   ObjectEnum(){_error_("Not implemented yet.");};
    4339                Object* copy(){_error_("Not implemented yet.");};
     
    4642};
    4743#endif  /* _KML_LATLONBOX_H */
    48 
  • issm/trunk/src/c/classes/objects/KML/KML_LineString.h

    r13395 r13975  
    3939                void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
    4040                int   Id(){_error_("Not implemented yet.");};
    41                 int   MyRank(){_error_("Not implemented yet.");};
    42                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    43                 int   MarshallSize(){_error_("Not implemented yet.");};
    44                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    4541                int   ObjectEnum(){_error_("Not implemented yet.");};
    4642                Object* copy(){_error_("Not implemented yet.");};
     
    4945};
    5046#endif  /* _KML_LINESTRING_H */
    51 
  • issm/trunk/src/c/classes/objects/KML/KML_LineStyle.cpp

    r13395 r13975  
    6363void  KML_LineStyle::DeepEcho(const char* indent){
    6464
    65         int   i;
    6665        bool  flag=true;
    6766
  • issm/trunk/src/c/classes/objects/KML/KML_LineStyle.h

    r13395 r13975  
    3232                void  Read(FILE* fid,char* kstr);
    3333                int   Id(){_error_("Not implemented yet.");};
    34                 int   MyRank(){_error_("Not implemented yet.");};
    35                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    36                 int   MarshallSize(){_error_("Not implemented yet.");};
    37                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    3834                int   ObjectEnum(){_error_("Not implemented yet.");};
    3935                Object* copy(){_error_("Not implemented yet.");};
     
    4238};
    4339#endif  /* _KML_LINESTYLE_H */
    44 
  • issm/trunk/src/c/classes/objects/KML/KML_LinearRing.h

    r13395 r13975  
    3939                void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
    4040                int   Id(){_error_("Not implemented yet.");};
    41                 int   MyRank(){_error_("Not implemented yet.");};
    42                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    43                 int   MarshallSize(){_error_("Not implemented yet.");};
    44                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    4541                int   ObjectEnum(){_error_("Not implemented yet.");};
    4642                Object* copy(){_error_("Not implemented yet.");};
     
    4945};
    5046#endif  /* _KML_LINEARRING_H */
    51 
  • issm/trunk/src/c/classes/objects/KML/KML_MultiGeometry.h

    r13395 r13975  
    3535                void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
    3636                int   Id(){_error_("Not implemented yet.");};
    37                 int   MyRank(){_error_("Not implemented yet.");};
    38                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    39                 int   MarshallSize(){_error_("Not implemented yet.");};
    40                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    4137                int   ObjectEnum(){_error_("Not implemented yet.");};
    4238                Object* copy(){_error_("Not implemented yet.");};
     
    4541};
    4642#endif  /* _KML_MULTIGEOMETRY_H */
    47 
  • issm/trunk/src/c/classes/objects/KML/KML_Object.h

    r13395 r13975  
    3232                virtual void  DeepEcho(const char* indent);
    3333                int   Id(){_error_("Not implemented yet.");};
    34                 int   MyRank(){_error_("Not implemented yet.");};
    35                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    36                 int   MarshallSize(){_error_("Not implemented yet.");};
    37                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    3834                int   ObjectEnum(){_error_("Not implemented yet.");};
    3935                Object* copy(){_error_("Not implemented yet.");};
     
    5450};
    5551#endif  /* _KML_OBJECT_H */
    56 
  • issm/trunk/src/c/classes/objects/KML/KML_Overlay.h

    r13395 r13975  
    3737                void  Read(FILE* fid,char* kstr);
    3838                int   Id(){_error_("Not implemented yet.");};
    39                 int   MyRank(){_error_("Not implemented yet.");};
    40                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    41                 int   MarshallSize(){_error_("Not implemented yet.");};
    42                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    4339                int   ObjectEnum(){_error_("Not implemented yet.");};
    4440                Object* copy(){_error_("Not implemented yet.");};
     
    4743};
    4844#endif  /* _KML_OVERLAY_H */
    49 
  • issm/trunk/src/c/classes/objects/KML/KML_Placemark.h

    r13395 r13975  
    3535                void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
    3636                int   Id(){_error_("Not implemented yet.");};
    37                 int   MyRank(){_error_("Not implemented yet.");};
    38                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    39                 int   MarshallSize(){_error_("Not implemented yet.");};
    40                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    4137                int   ObjectEnum(){_error_("Not implemented yet.");};
    4238                Object* copy(){_error_("Not implemented yet.");};
     
    4541};
    4642#endif  /* _KML_PLACEMARK_H */
    47 
  • issm/trunk/src/c/classes/objects/KML/KML_Point.h

    r13395 r13975  
    3737                void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
    3838                int   Id(){_error_("Not implemented yet.");};
    39                 int   MyRank(){_error_("Not implemented yet.");};
    40                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    41                 int   MarshallSize(){_error_("Not implemented yet.");};
    42                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    4339                int   ObjectEnum(){_error_("Not implemented yet.");};
    4440                Object* copy(){_error_("Not implemented yet.");};
     
    4743};
    4844#endif  /* _KML_POINT_H */
    49 
  • issm/trunk/src/c/classes/objects/KML/KML_PolyStyle.cpp

    r13395 r13975  
    6565void  KML_PolyStyle::DeepEcho(const char* indent){
    6666
    67         int   i;
    6867        bool  flag=true;
    6968
  • issm/trunk/src/c/classes/objects/KML/KML_PolyStyle.h

    r13395 r13975  
    3333                void  Read(FILE* fid,char* kstr);
    3434                int   Id(){_error_("Not implemented yet.");};
    35                 int   MyRank(){_error_("Not implemented yet.");};
    36                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    37                 int   MarshallSize(){_error_("Not implemented yet.");};
    38                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    3935                int   ObjectEnum(){_error_("Not implemented yet.");};
    4036                Object* copy(){_error_("Not implemented yet.");};
     
    4339};
    4440#endif  /* _KML_POLYSTYLE_H */
    45 
  • issm/trunk/src/c/classes/objects/KML/KML_Polygon.cpp

    r13395 r13975  
    250250                        }
    251251
    252 
    253252                else if (!strncmp(kstri,"<",1))
    254253                        KML_Geometry::Read(fid,kstri);
  • issm/trunk/src/c/classes/objects/KML/KML_Polygon.h

    r13395 r13975  
    4141                void  WriteExp(FILE* fid,const char* nstr,int sgn,double cm,double sp);
    4242                int   Id(){_error_("Not implemented yet.");};
    43                 int   MyRank(){_error_("Not implemented yet.");};
    44                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    45                 int   MarshallSize(){_error_("Not implemented yet.");};
    46                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    4743                int   ObjectEnum(){_error_("Not implemented yet.");};
    4844                Object* copy(){_error_("Not implemented yet.");};
     
    5147};
    5248#endif  /* _KML_POLYGON_H */
    53 
  • issm/trunk/src/c/classes/objects/KML/KML_Style.h

    r13395 r13975  
    3939                void  Read(FILE* fid,char* kstr);
    4040                int   Id(){_error_("Not implemented yet.");};
    41                 int   MyRank(){_error_("Not implemented yet.");};
    42                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    43                 int   MarshallSize(){_error_("Not implemented yet.");};
    44                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    4541                int   ObjectEnum(){_error_("Not implemented yet.");};
    4642                Object* copy(){_error_("Not implemented yet.");};
     
    4945};
    5046#endif  /* _KML_STYLE_H */
    51 
  • issm/trunk/src/c/classes/objects/KML/KML_StyleSelector.cpp

    r13395 r13975  
    9393}
    9494/*}}}*/
    95 
  • issm/trunk/src/c/classes/objects/KML/KML_StyleSelector.h

    r13395 r13975  
    3030                void  Read(FILE* fid,char* kstr);
    3131                int   Id(){_error_("Not implemented yet.");};
    32                 int   MyRank(){_error_("Not implemented yet.");};
    33                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    34                 int   MarshallSize(){_error_("Not implemented yet.");};
    35                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    3632                int   ObjectEnum(){_error_("Not implemented yet.");};
    3733                Object* copy(){_error_("Not implemented yet.");};
     
    4036};
    4137#endif  /* _KML_STYLESELECTOR_H */
    42 
  • issm/trunk/src/c/classes/objects/KML/KML_SubStyle.cpp

    r13395 r13975  
    9393}
    9494/*}}}*/
    95 
  • issm/trunk/src/c/classes/objects/KML/KML_SubStyle.h

    r13395 r13975  
    3030                void  Read(FILE* fid,char* kstr);
    3131                int   Id(){_error_("Not implemented yet.");};
    32                 int   MyRank(){_error_("Not implemented yet.");};
    33                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    34                 int   MarshallSize(){_error_("Not implemented yet.");};
    35                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    3632                int   ObjectEnum(){_error_("Not implemented yet.");};
    3733                Object* copy(){_error_("Not implemented yet.");};
     
    4036};
    4137#endif  /* _KML_SUBSTYLE_H */
    42 
  • issm/trunk/src/c/classes/objects/KML/KML_Unknown.cpp

    r13395 r13975  
    7979                valuei=xNew<char>(strlen(value)+1);
    8080                memcpy(valuei,value,(strlen(value)+1)*sizeof(char));
    81        
     81
    8282                vtoken=strtok(valuei,nl);
    8383                if(flag) _pprintString_(indent << "         value: \"" << vtoken);
    84    
     84
    8585                while (vtoken=strtok(NULL,nl))
    8686                        if(flag) _pprintString_("\n" << indent << "                 " << vtoken);
     
    110110                valuei=xNew<char>(strlen(value)+1);
    111111                memcpy(valuei,value,(strlen(value)+1)*sizeof(char));
    112        
     112
    113113                vtoken=strtok(valuei,nl);
    114114                fprintf(filout,"%s  %s\n",indent,vtoken);
    115    
     115
    116116                while (vtoken=strtok(NULL,nl))
    117117                        fprintf(filout,"%s  %s\n",indent,vtoken);
  • issm/trunk/src/c/classes/objects/KML/KML_Unknown.h

    r13395 r13975  
    3333                void  Read(FILE* fid,char* kstr);
    3434                int   Id(){_error_("Not implemented yet.");};
    35                 int   MyRank(){_error_("Not implemented yet.");};
    36                 void  Marshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    37                 int   MarshallSize(){_error_("Not implemented yet.");};
    38                 void  Demarshall(char** pmarshalled_dataset){_error_("Not implemented yet.");};
    3935                int   ObjectEnum(){_error_("Not implemented yet.");};
    4036                Object* copy(){_error_("Not implemented yet.");};
     
    4339};
    4440#endif  /* _KML_UNKNOWN_H */
    45 
  • issm/trunk/src/c/classes/objects/Loads/Friction.cpp

    r13395 r13975  
    191191
    192192        /*diverse: */
    193         int     i;
    194193        IssmDouble  r,s;
    195194        IssmDouble  vx,vy,vz,vmag;
     
    257256
    258257        /*diverse: */
    259         int     i;
    260258        IssmDouble  r,s;
    261259        IssmDouble  vx,vy,vz,vmag;
  • issm/trunk/src/c/classes/objects/Loads/Friction.h

    r13395 r13975  
    2525                Friction(const char* element_type, Inputs* inputs,Matpar* matpar, int analysis_type);
    2626                ~Friction();
    27        
     27
    2828                void  Echo(void);
    2929                void  GetAlpha2(IssmDouble* palpha2, GaussTria* gauss,int vxenum,int vyenum,int vzenum);
  • issm/trunk/src/c/classes/objects/Loads/Icefront.cpp

    r13395 r13975  
    5252        int  icefront_node_ids[NUMVERTICESQUA]; //initialize with largest size
    5353        int  icefront_fill;
    54        
     54
    5555        /*find parameters: */
    5656        iomodel->Constant(&dim,MeshDimensionEnum);
     
    9090        /*Fill*/
    9191        icefront_fill=reCast<int>(iomodel->Data(DiagnosticIcefrontEnum)[segment_width*i+segment_width-1]);
    92        
     92
    9393        /*Ok, we have everything to build the object: */
    9494        this->id=icefront_id;
     
    104104        this->inputs->AddInput(new IntInput(FillEnum,icefront_fill));
    105105        this->inputs->AddInput(new IntInput(TypeEnum,in_icefront_type));
    106        
     106
    107107        //parameters and hooked fields: we still can't point to them, they may not even exist. Configure will handle this.
    108108        this->parameters=NULL;
     
    111111        this->matpar= NULL;
    112112}
    113 
    114113
    115114/*}}}*/
     
    157156int    Icefront::Id(void){ return id; }
    158157/*}}}*/
    159 /*FUNCTION Icefront::MyRank {{{*/
    160 int    Icefront::MyRank(void){
    161         extern int my_rank;
    162         return my_rank;
    163 }
    164 /*}}}*/
    165158/*FUNCTION Icefront::ObjectEnum{{{*/
    166159int Icefront::ObjectEnum(void){
     
    172165/*FUNCTION Icefront::copy {{{*/
    173166Object* Icefront::copy() {
    174        
     167
    175168        Icefront* icefront=NULL;
    176169
     
    278271}
    279272/*}}}*/
     273/*FUNCTION Icefront::GetNodesSidList{{{*/
     274void Icefront::GetNodesSidList(int* sidlist){
     275
     276        int type;
     277        inputs->GetInputValue(&type,TypeEnum);
     278        _assert_(sidlist);
     279        _assert_(nodes);
     280
     281        switch(type){
     282                case MacAyeal2dIceFrontEnum:
     283                case MacAyeal3dIceFrontEnum:
     284                        for(int i=0;i<NUMVERTICESSEG;i++) sidlist[i]=nodes[i]->Sid();
     285                        return;
     286#ifdef _HAVE_3D_
     287                case PattynIceFrontEnum:
     288                case StokesIceFrontEnum:
     289                        for(int i=0;i<NUMVERTICESQUA;i++) sidlist[i]=nodes[i]->Sid();
     290                        return;
     291#endif
     292                default:
     293                        _error_("Icefront type " << EnumToStringx(type) << " not supported yet");
     294        }
     295}
     296/*}}}*/
     297/*FUNCTION Icefront::GetNumberOfNodes{{{*/
     298int Icefront::GetNumberOfNodes(void){
     299
     300        int type;
     301        inputs->GetInputValue(&type,TypeEnum);
     302
     303        switch(type){
     304                case MacAyeal2dIceFrontEnum:
     305                        return NUMVERTICESSEG;
     306#ifdef _HAVE_3D_
     307                case MacAyeal3dIceFrontEnum:
     308                        return NUMVERTICESSEG;
     309                case PattynIceFrontEnum:
     310                        return NUMVERTICESQUA;
     311                case StokesIceFrontEnum:
     312                        return NUMVERTICESQUA;
     313#endif
     314                default:
     315                        _error_("Icefront type " << EnumToStringx(type) << " not supported yet");
     316        }
     317
     318}
     319/*}}}*/
     320/*FUNCTION Icefront::IsPenalty{{{*/
     321bool Icefront::IsPenalty(void){
     322        return false;
     323}
     324/*}}}*/
    280325/*FUNCTION Icefront::PenaltyCreateKMatrix {{{*/
    281326void  Icefront::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs, IssmDouble kmax){
     
    293338void  Icefront::PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){
    294339        this->PenaltyCreateKMatrix(Jff,NULL,kmax);
     340}
     341/*}}}*/
     342/*FUNCTION Icefront::SetwiseNodeConnectivity{{{*/
     343void Icefront::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
     344
     345        /*Output */
     346        int d_nz = 0;
     347        int o_nz = 0;
     348
     349        /*Loop over all nodes*/
     350        for(int i=0;i<this->GetNumberOfNodes();i++){
     351
     352                if(!flags[this->nodes[i]->Sid()]){
     353
     354                        /*flag current node so that no other element processes it*/
     355                        flags[this->nodes[i]->Sid()]=true;
     356
     357                        /*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
     358                        switch(set2_enum){
     359                                case FsetEnum:
     360                                        if(nodes[i]->indexing.fsize){
     361                                                if(this->nodes[i]->IsClone())
     362                                                 o_nz += 1;
     363                                                else
     364                                                 d_nz += 1;
     365                                        }
     366                                        break;
     367                                case GsetEnum:
     368                                        if(nodes[i]->indexing.gsize){
     369                                                if(this->nodes[i]->IsClone())
     370                                                 o_nz += 1;
     371                                                else
     372                                                 d_nz += 1;
     373                                        }
     374                                        break;
     375                                case SsetEnum:
     376                                        if(nodes[i]->indexing.ssize){
     377                                                if(this->nodes[i]->IsClone())
     378                                                 o_nz += 1;
     379                                                else
     380                                                 d_nz += 1;
     381                                        }
     382                                        break;
     383                                default: _error_("not supported");
     384                        }
     385                }
     386        }
     387
     388        /*Assign output pointers: */
     389        *pd_nz=d_nz;
     390        *po_nz=o_nz;
    295391}
    296392/*}}}*/
     
    479575ElementVector* Icefront::CreatePVectorDiagnosticMacAyeal3d(void){
    480576
    481         Icefront* icefront=NULL;
    482         Penta*    penta=NULL;
    483         Tria*     tria=NULL;
    484         bool      onbed;
     577        Icefront *icefront = NULL;
     578        Penta    *penta    = NULL;
     579        Tria     *tria     = NULL;
    485580
    486581        /*Cast element onto Penta*/
     
    663758void  Icefront::GetDofList(int** pdoflist,int approximation_enum,int setenum){
    664759
    665         int i,j;
    666760        int numberofdofs=0;
    667761        int count=0;
     
    672766        int* doflist=NULL;
    673767
    674        
    675768        /*recover type: */
    676769        inputs->GetInputValue(&type,TypeEnum);
     
    678771        /*Some checks for debugging*/
    679772        _assert_(nodes);
    680                
     773
    681774        /*How many nodes? :*/
    682775        if(type==MacAyeal2dIceFrontEnum || type==MacAyeal3dIceFrontEnum)
     
    684777        else
    685778         numberofnodes=4;
    686        
     779
    687780        /*Figure out size of doflist: */
    688         for(i=0;i<numberofnodes;i++){
     781        for(int i=0;i<numberofnodes;i++){
    689782                numberofdofs+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
    690783        }
     
    695788        /*Populate: */
    696789        count=0;
    697         for(i=0;i<numberofnodes;i++){
     790        for(int i=0;i<numberofnodes;i++){
    698791                nodes[i]->GetDofList(doflist+count,approximation_enum,setenum);
    699792                count+=nodes[i]->GetNumberOfDofs(approximation_enum,setenum);
  • issm/trunk/src/c/classes/objects/Loads/Icefront.h

    r13395 r13975  
    4848                void  DeepEcho();
    4949                int   Id();
    50                 int   MyRank();
    5150                int   ObjectEnum();
    5251                Object* copy();
     
    7271                void  CreatePVector(Vector<IssmDouble>* pf);
    7372                void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff);
     73                int   GetNumberOfNodes(void);
     74                void  GetNodesSidList(int* sidlist);
     75                bool  IsPenalty(void);
    7476                void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
    7577                void  PenaltyCreatePVector(Vector<IssmDouble>*  pf, IssmDouble kmax);
    7678                void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax);
     79                void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
    7780                bool  InAnalysis(int analysis_type);
    7881                /*}}}*/
  • issm/trunk/src/c/classes/objects/Loads/Load.h

    r13395 r13975  
    44 * It is derived from Load, so DataSets can contain them.
    55 */
    6 
    76
    87#ifndef _LOAD_H_
     
    2524
    2625                virtual       ~Load(){};
    27                
    28                 /*Virtual functions: {{{*/
    2926                virtual void  Configure(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
     27                virtual bool  IsPenalty(void)=0;
     28                virtual int   GetNumberOfNodes(void)=0;
     29                virtual void  GetNodesSidList(int* sidlist)=0;
    3030                virtual void  SetCurrentConfiguration(Elements* elements,Loads* loads,Nodes* nodes,Vertices* vertices,Materials* materials,Parameters* parameters)=0;
    3131                virtual void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs)=0;
     
    3636                virtual void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax)=0;
    3737                virtual bool  InAnalysis(int analysis_type)=0;
    38                 /*}}}*/
     38                virtual void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum)=0;
    3939};
    4040#endif
  • issm/trunk/src/c/classes/objects/Loads/Numericalflux.cpp

    r13395 r13975  
    3434}
    3535/*}}}*/
    36 /*}}}*//*FUNCTION Numericalflux::Numericalflux(int id, int i, IoModel* iomodel, int analysis_type) {{{*/
     36/*FUNCTION Numericalflux::Numericalflux(int id, int i, IoModel* iomodel, int analysis_type) {{{*/
    3737Numericalflux::Numericalflux(int numericalflux_id,int i, IoModel* iomodel, int in_analysis_type){
    3838
     
    175175        _printLine_("   inputs");
    176176        inputs->DeepEcho();
    177        
     177
    178178}               
    179179/*}}}*/
     
    183183}
    184184/*}}}*/
    185 /*FUNCTION Numericalflux::MyRank {{{*/
    186 int    Numericalflux::MyRank(void){
    187         extern int my_rank;
    188         return my_rank;
    189 }
    190 /*}}}*/
    191185/*FUNCTION Numericalflux::ObjectEnum{{{*/
    192186int Numericalflux::ObjectEnum(void){
     
    198192/*FUNCTION Numericalflux::copy {{{*/
    199193Object* Numericalflux::copy() {
    200        
     194
    201195        Numericalflux* numericalflux=NULL;
    202196
     
    311305}
    312306/*}}}*/
     307/*FUNCTION Numericalflux::GetNodesSidList{{{*/
     308void Numericalflux::GetNodesSidList(int* sidlist){
     309
     310        int type;
     311        inputs->GetInputValue(&type,TypeEnum);
     312        _assert_(sidlist);
     313        _assert_(nodes);
     314
     315        switch(type){
     316                case InternalEnum:
     317                        for(int i=0;i<NUMVERTICES_INTERNAL;i++) sidlist[i]=nodes[i]->Sid();
     318                        return;
     319                case BoundaryEnum:
     320                        for(int i=0;i<NUMVERTICES_BOUNDARY;i++) sidlist[i]=nodes[i]->Sid();
     321                        return;
     322                default:
     323                        _error_("Numericalflux type " << EnumToStringx(type) << " not supported yet");
     324        }
     325}
     326/*}}}*/
     327/*FUNCTION Numericalflux::GetNumberOfNodes{{{*/
     328int Numericalflux::GetNumberOfNodes(void){
     329
     330        int type;
     331        inputs->GetInputValue(&type,TypeEnum);
     332
     333        switch(type){
     334                case InternalEnum:
     335                        return NUMVERTICES_INTERNAL;
     336                case BoundaryEnum:
     337                        return NUMVERTICES_BOUNDARY;
     338                default:
     339                        _error_("Numericalflux type " << EnumToStringx(type) << " not supported yet");
     340        }
     341
     342}
     343/*}}}*/
     344/*FUNCTION Numericalflux::IsPenalty{{{*/
     345bool Numericalflux::IsPenalty(void){
     346        return false;
     347}
     348/*}}}*/
    313349/*FUNCTION Numericalflux::PenaltyCreateKMatrix {{{*/
    314350void  Numericalflux::PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs,IssmDouble kmax){
     
    331367        if (in_analysis_type==this->analysis_type) return true;
    332368        else return false;
     369}
     370/*}}}*/
     371/*FUNCTION Numericalflux::SetwiseNodeConnectivity{{{*/
     372void Numericalflux::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
     373
     374        /*Output */
     375        int d_nz = 0;
     376        int o_nz = 0;
     377
     378        /*Loop over all nodes*/
     379        for(int i=0;i<this->GetNumberOfNodes();i++){
     380
     381                if(!flags[this->nodes[i]->Sid()]){
     382
     383                        /*flag current node so that no other element processes it*/
     384                        flags[this->nodes[i]->Sid()]=true;
     385
     386                        /*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
     387                        switch(set2_enum){
     388                                case FsetEnum:
     389                                        if(nodes[i]->indexing.fsize){
     390                                                if(this->nodes[i]->IsClone())
     391                                                 o_nz += 1;
     392                                                else
     393                                                 d_nz += 1;
     394                                        }
     395                                        break;
     396                                case GsetEnum:
     397                                        if(nodes[i]->indexing.gsize){
     398                                                if(this->nodes[i]->IsClone())
     399                                                 o_nz += 1;
     400                                                else
     401                                                 d_nz += 1;
     402                                        }
     403                                        break;
     404                                case SsetEnum:
     405                                        if(nodes[i]->indexing.ssize){
     406                                                if(this->nodes[i]->IsClone())
     407                                                 o_nz += 1;
     408                                                else
     409                                                 d_nz += 1;
     410                                        }
     411                                        break;
     412                                default: _error_("not supported");
     413                        }
     414                }
     415        }
     416
     417        /*Assign output pointers: */
     418        *pd_nz=d_nz;
     419        *po_nz=o_nz;
    333420}
    334421/*}}}*/
     
    410497                for(i=0;i<numdof;i++) for(j=0;j<numdof;j++) Ke->values[i*numdof+j]+=Ke_g2[i][j];
    411498        }
    412        
     499
    413500        /*Clean up and return*/
    414501        delete gauss;
     
    702789
    703790        /* Intermediaries*/
    704         int        i,j,ig,index1,index2;
     791        int        i,ig,index1,index2;
    705792        IssmDouble     DL,Jdet,dt,vx,vy,mean_vx,mean_vy,UdotN,thickness;
    706793        IssmDouble     xyz_list[NUMVERTICES_BOUNDARY][3];
     
    796883
    797884        /* Intermediaries*/
    798         int        i,j,ig,index1,index2;
    799         IssmDouble     DL,Jdet,vx,vy,mean_vx,mean_vy,UdotN,thickness;
    800         IssmDouble     xyz_list[NUMVERTICES_BOUNDARY][3];
    801         IssmDouble     normal[2];
    802         IssmDouble     L[numdof];
     885        int        i,ig,index1,index2;
     886        IssmDouble DL,Jdet,vx,vy,mean_vx,mean_vy,UdotN,thickness;
     887        IssmDouble xyz_list[NUMVERTICES_BOUNDARY][3];
     888        IssmDouble normal[2];
     889        IssmDouble L[numdof];
    803890        GaussTria *gauss;
    804891
  • issm/trunk/src/c/classes/objects/Loads/Numericalflux.h

    r13395 r13975  
    2020
    2121        public:
    22                 int         id;
     22                int id;
    2323                int analysis_type;
    2424
    2525                /*Hooks*/
    26                 Hook*       helement;
    27                 Hook*       hnodes;
     26                Hook *helement;
     27                Hook *hnodes;
    2828
    2929                /*Corresponding fields*/
    30                 Element* element;
    31                 Node**   nodes;
    32 
    33                 Parameters *parameters;
    34                 Inputs     *inputs;
    35 
     30                Element     *element;
     31                Node       **nodes;
     32                Parameters  *parameters;
     33                Inputs      *inputs;
    3634
    3735                /*Numericalflux constructors,destructors {{{*/
     
    4442                void  DeepEcho();
    4543                int   Id();
    46                 int   MyRank();
    4744                int   ObjectEnum();
    4845                Object* copy();
     
    6764                void  CreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* Kfs);
    6865                void  CreatePVector(Vector<IssmDouble>* pf);
     66                void  GetNodesSidList(int* sidlist);
     67                int   GetNumberOfNodes(void);
    6968                void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
     69                bool  IsPenalty(void);
    7070                void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){_error_("Not implemented yet");};
    7171                void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
    7272                void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
     73                void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
    7374                bool  InAnalysis(int analysis_type);
    7475                /*}}}*/
  • issm/trunk/src/c/classes/objects/Loads/Pengrid.cpp

    r13395 r13975  
    1919#include "../../../Container/Container.h"
    2020/*}}}*/
    21        
     21
    2222/*Element macros*/
    2323#define NUMVERTICES   1
     
    3434        this->hmatpar=NULL;
    3535        this->matpar=NULL;
    36        
     36
    3737        /*not active, not zigzagging: */
    3838        active=0;
     
    4444Pengrid::Pengrid(int id, int index, IoModel* iomodel, int in_analysis_type){ //i is the element index
    4545
    46         int i,j;
    4746        int pengrid_node_id;
    4847        int pengrid_matpar_id;
     
    6463        this->id=id;
    6564        this->analysis_type=in_analysis_type;
    66        
     65
    6766        /*hooks: */
    6867        pengrid_node_id=iomodel->nodecounter+index+1;
     
    9998}
    10099/*}}}*/
    101                        
     100
    102101/*Object virtual functions definitions:*/
    103102/*FUNCTION Pengrid::Echo {{{*/
     
    126125int    Pengrid::Id(void){ return id; }
    127126/*}}}*/
    128 /*FUNCTION Pengrid::MyRank {{{*/
    129 int    Pengrid::MyRank(void){
    130         extern int my_rank;
    131         return my_rank;
    132 }
    133 /*}}}*/
    134127/*FUNCTION Pengrid::ObjectEnum{{{*/
    135128int Pengrid::ObjectEnum(void){
     
    140133/*FUNCTION Icefront::copy {{{*/
    141134Object* Pengrid::copy() {
    142        
     135
    143136        Pengrid* pengrid=NULL;
    144137
     
    214207        return;
    215208
     209}
     210/*}}}*/
     211/*FUNCTION Pengrid::GetNodesSidList{{{*/
     212void Pengrid::GetNodesSidList(int* sidlist){
     213
     214        _assert_(sidlist);
     215        _assert_(node);
     216
     217        sidlist[0]=node->Sid();
     218}
     219/*}}}*/
     220/*FUNCTION Pengrid::GetNumberOfNodes{{{*/
     221int Pengrid::GetNumberOfNodes(void){
     222
     223        return NUMVERTICES;
    216224}
    217225/*}}}*/
     
    287295}
    288296/*}}}*/
     297/*FUNCTION Pengrid::IsPenalty{{{*/
     298bool Pengrid::IsPenalty(void){
     299        return true;
     300}
     301/*}}}*/
     302/*FUNCTION Pengrid::SetwiseNodeConnectivity{{{*/
     303void Pengrid::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
     304
     305        /*Output */
     306        int d_nz = 0;
     307        int o_nz = 0;
     308
     309        if(!flags[this->node->Sid()]){
     310
     311                /*flag current node so that no other element processes it*/
     312                flags[this->node->Sid()]=true;
     313
     314                /*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
     315                switch(set2_enum){
     316                        case FsetEnum:
     317                                if(node->indexing.fsize){
     318                                        if(this->node->IsClone())
     319                                         o_nz += 1;
     320                                        else
     321                                         d_nz += 1;
     322                                }
     323                                break;
     324                        case GsetEnum:
     325                                if(node->indexing.gsize){
     326                                        if(this->node->IsClone())
     327                                         o_nz += 1;
     328                                        else
     329                                         d_nz += 1;
     330                                }
     331                                break;
     332                        case SsetEnum:
     333                                if(node->indexing.ssize){
     334                                        if(this->node->IsClone())
     335                                         o_nz += 1;
     336                                        else
     337                                         d_nz += 1;
     338                                }
     339                                break;
     340                        default: _error_("not supported");
     341                }
     342        }
     343
     344        /*Assign output pointers: */
     345        *pd_nz=d_nz;
     346        *po_nz=o_nz;
     347}
     348/*}}}*/
    289349
    290350/*Update virtual functions definitions:*/
     
    401461        /*recover pointers: */
    402462        Penta* penta=(Penta*)element;
    403        
     463
    404464        /*check that pengrid is not a clone (penalty to be added only once)*/
    405465        if (node->IsClone()){
     
    415475        //Recover our data:
    416476        parameters->FindParam(&penalty_lock,ThermalPenaltyLockEnum);
    417        
     477
    418478        //Compute pressure melting point
    419479        t_pmp=matpar->TMeltingPoint(pressure);
     
    427487                new_active=0;
    428488        }
    429 
    430489
    431490        //Figure out stability of this penalty
     
    456515/*FUNCTION Pengrid::PenaltyCreateKMatrixDiagnosticStokes {{{*/
    457516ElementMatrix* Pengrid::PenaltyCreateKMatrixDiagnosticStokes(IssmDouble kmax){
    458        
     517
    459518        const int numdof = NUMVERTICES *NDOF4;
    460519        IssmDouble    slope[2];
     
    505564        penta->GetInputValue(&temperature,node,TemperatureEnum);
    506565        parameters->FindParam(&penalty_factor,ThermalPenaltyFactorEnum);
    507        
     566
    508567        /*Compute pressure melting point*/
    509568        t_pmp=matpar->GetMeltingPoint()-matpar->GetBeta()*pressure;
     
    539598/*FUNCTION Pengrid::PenaltyCreatePVectorMelting {{{*/
    540599ElementVector* Pengrid::PenaltyCreatePVectorMelting(IssmDouble kmax){
    541        
     600
    542601        const int numdof=NUMVERTICES*NDOF1;
    543602        IssmDouble pressure;
  • issm/trunk/src/c/classes/objects/Loads/Pengrid.h

    r13395 r13975  
    2020                int             id;
    2121                int analysis_type;
    22                
     22
    2323                /*Hooks*/
    2424                Hook* hnode;  //hook to 1 node
     
    3333                Parameters* parameters; //pointer to solution parameters
    3434                Inputs*  inputs;
    35        
     35
    3636                /*internals: */
    3737                int active;
     
    4949                void  DeepEcho();
    5050                int   Id();
    51                 int   MyRank();
    5251                int   ObjectEnum();
    5352                Object* copy();
     
    7372                void  CreatePVector(Vector<IssmDouble>* pf);
    7473                void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
     74                void  GetNodesSidList(int* sidlist);
     75                int   GetNumberOfNodes(void);
     76                bool  IsPenalty(void);
    7577                void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){_error_("Not implemented yet");};
    7678                void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
    7779                void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
     80                void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
    7881                bool  InAnalysis(int analysis_type);
    7982                /*}}}*/
     
    97100
    98101#endif  /* _PENGRID_H_ */
    99 
    100 
  • issm/trunk/src/c/classes/objects/Loads/Penpair.cpp

    r13395 r13975  
    3434/*FUNCTION Penpair::creation {{{*/
    3535Penpair::Penpair(int penpair_id, int* penpair_node_ids,int in_analysis_type){
    36        
     36
    3737        this->id=penpair_id;
    3838        this->analysis_type=in_analysis_type;
     
    4040        this->parameters=NULL;
    4141        this->nodes=NULL;
    42        
     42
    4343        return;
    4444}
     
    5454/*FUNCTION Penpair::Echo {{{*/
    5555void Penpair::Echo(void){
    56 
    57         int i;
    5856
    5957        _printLine_("Penpair:");
     
    6159        _printLine_("   analysis_type: " << EnumToStringx(analysis_type));
    6260        hnodes->Echo();
    63        
     61
    6462        return;
    6563}
     
    7977int    Penpair::Id(void){ return id; }
    8078/*}}}*/
    81 /*FUNCTION Penpair::MyRank {{{*/
    82 int    Penpair::MyRank(void){
    83         extern int my_rank;
    84         return my_rank;
    85 }
    86 /*}}}*/
    8779/*FUNCTION Penpair::ObjectEnum{{{*/
    8880int Penpair::ObjectEnum(void){
     
    9385/*FUNCTION Penpair::copy {{{*/
    9486Object* Penpair::copy() {
    95        
     87
    9688        Penpair* penpair=NULL;
    9789
     
    113105}
    114106/*}}}*/
    115                
     107
    116108/*Load virtual functions definitions:*/
    117109/*FUNCTION Penpair::Configure {{{*/
     
    154146void  Penpair::CreateJacobianMatrix(Matrix<IssmDouble>* Jff){
    155147        this->CreateKMatrix(Jff,NULL);
     148}
     149/*}}}*/
     150/*FUNCTION Penpair::GetNodesSidList{{{*/
     151void Penpair::GetNodesSidList(int* sidlist){
     152
     153        _assert_(sidlist);
     154        _assert_(nodes);
     155
     156        for(int i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->Sid();
     157}
     158/*}}}*/
     159/*FUNCTION Penpair::GetNumberOfNodes{{{*/
     160int Penpair::GetNumberOfNodes(void){
     161
     162        return NUMVERTICES;
     163}
     164/*}}}*/
     165/*FUNCTION Penpair::IsPenalty{{{*/
     166bool Penpair::IsPenalty(void){
     167        return true;
    156168}
    157169/*}}}*/
     
    197209        if (in_analysis_type==this->analysis_type)return true;
    198210        else return false;
     211}
     212/*}}}*/
     213/*FUNCTION Penpair::SetwiseNodeConnectivity{{{*/
     214void Penpair::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
     215
     216        /*Output */
     217        int d_nz = 0;
     218        int o_nz = 0;
     219
     220        /*Loop over all nodes*/
     221        for(int i=0;i<NUMVERTICES;i++){
     222
     223                if(!flags[this->nodes[i]->Sid()]){
     224
     225                        /*flag current node so that no other element processes it*/
     226                        flags[this->nodes[i]->Sid()]=true;
     227
     228                        /*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
     229                        switch(set2_enum){
     230                                case FsetEnum:
     231                                        if(nodes[i]->indexing.fsize){
     232                                                if(this->nodes[i]->IsClone())
     233                                                 o_nz += 1;
     234                                                else
     235                                                 d_nz += 1;
     236                                        }
     237                                        break;
     238                                case GsetEnum:
     239                                        if(nodes[i]->indexing.gsize){
     240                                                if(this->nodes[i]->IsClone())
     241                                                 o_nz += 1;
     242                                                else
     243                                                 d_nz += 1;
     244                                        }
     245                                        break;
     246                                case SsetEnum:
     247                                        if(nodes[i]->indexing.ssize){
     248                                                if(this->nodes[i]->IsClone())
     249                                                 o_nz += 1;
     250                                                else
     251                                                 d_nz += 1;
     252                                        }
     253                                        break;
     254                                default: _error_("not supported");
     255                        }
     256                }
     257        }
     258
     259        /*Assign output pointers: */
     260        *pd_nz=d_nz;
     261        *po_nz=o_nz;
    199262}
    200263/*}}}*/
     
    270333/*FUNCTION Penpair::PenaltyCreateKMatrixDiagnosticMacAyealPattyn {{{*/
    271334ElementMatrix* Penpair::PenaltyCreateKMatrixDiagnosticMacAyealPattyn(IssmDouble kmax){
    272        
     335
    273336        const int numdof=NUMVERTICES*NDOF2;
    274337        IssmDouble penalty_offset;
     
    297360/*FUNCTION Penpair::PenaltyCreateKMatrixDiagnosticStokes {{{*/
    298361ElementMatrix* Penpair::PenaltyCreateKMatrixDiagnosticStokes(IssmDouble kmax){
    299        
     362
    300363        const int numdof=NUMVERTICES*NDOF4;
    301364        IssmDouble penalty_offset;
     
    317380        Ke->values[5*numdof+1]=-kmax*pow((IssmDouble)10.0,penalty_offset);
    318381        Ke->values[5*numdof+5]=+kmax*pow((IssmDouble)10.0,penalty_offset);
    319        
     382
    320383        Ke->values[2*numdof+2]=+kmax*pow((IssmDouble)10.0,penalty_offset);
    321384        Ke->values[2*numdof+6]=-kmax*pow((IssmDouble)10.0,penalty_offset);
  • issm/trunk/src/c/classes/objects/Loads/Penpair.h

    r13395 r13975  
    1717
    1818        private:
    19                 int             id;
    20                 int analysis_type;
    21                
    22                 Hook* hnodes;  //hook to 2 nodes
    23                 Node** nodes;
    24 
    25                 Parameters* parameters; //pointer to solution parameters
     19                int          id;
     20                int          analysis_type;
     21                Hook        *hnodes;          //hook to 2 nodes
     22                Node       **nodes;
     23                Parameters  *parameters;      //pointer to solution parameters
    2624
    2725        public:
     
    3634                void  DeepEcho();
    3735                int   Id();
    38                 int   MyRank();
    3936                int   ObjectEnum();
    4037                Object* copy();
     
    6057                void  CreatePVector(Vector<IssmDouble>* pf);
    6158                void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff);
     59                void  GetNodesSidList(int* sidlist);
     60                int   GetNumberOfNodes(void);
     61                bool  IsPenalty(void);
    6262                void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff,Matrix<IssmDouble>* Kfs,IssmDouble kmax);
    6363                void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
    6464                void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax);
     65                void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
    6566                bool  InAnalysis(int analysis_type);
    6667                /*}}}*/
     
    7475
    7576#endif  /* _PENPAIR_H_ */
    76 
    77 
  • issm/trunk/src/c/classes/objects/Loads/Riftfront.cpp

    r13395 r13975  
    9797        //intialize inputs, and add as many inputs per element as requested:
    9898        this->inputs=new Inputs();
    99                
     99
    100100        riftfront_type=SegmentRiftfrontEnum;
    101101        riftfront_fill = reCast<int,IssmDouble>(*(iomodel->Data(RiftsRiftstructEnum)+RIFTINFOSIZE*i+7));
     
    109109        this->inputs->AddInput(new DoubleInput(FractionIncrementEnum,riftfront_fractionincrement));
    110110        this->inputs->AddInput(new BoolInput(SegmentOnIceShelfEnum,riftfront_shelf));
    111        
     111
    112112        //parameters and hooked fields: we still can't point to them, they may not even exist. Configure will handle this.
    113113        this->parameters=NULL;
     
    115115        this->elements= NULL;
    116116        this->matpar= NULL;
    117                
     117
    118118}
    119119/*}}}*/
     
    137137        IssmDouble friction,fractionincrement;
    138138
    139        
    140139        /*recover some inputs first: */
    141140        input=(Input*)this->inputs->GetInput(FillEnum); input->GetInputValue(&fill);
     
    165164        _printLine_("   state: " << state);
    166165        _printLine_("   frozen: " << (frozen ? "true":"false"));
    167                
     166
    168167}
    169168/*}}}*/
     
    186185int    Riftfront::Id(void){ return id; }
    187186/*}}}*/
    188 /*FUNCTION Riftfront::MyRank {{{*/
    189 int    Riftfront::MyRank(void){
    190         extern int my_rank;
    191         return my_rank;
    192 }
    193 /*}}}*/
    194187/*FUNCTION Riftfront::ObjectEnum{{{*/
    195188int Riftfront::ObjectEnum(void){
     
    201194/*FUNCTION Riftfront::copy {{{*/
    202195Object* Riftfront::copy() {
    203        
     196
    204197        Riftfront* riftfront=NULL;
    205198
     
    240233        riftfront->length=this->length;
    241234        riftfront->fraction=this->fraction;
    242        
     235
    243236        return riftfront;
    244237
    245238}
    246239/*}}}*/
    247                
     240
    248241/*Update virtual functions definitions:*/
    249242/*FUNCTION Riftfront::InputUpdateFromConstant(bool constant,int name) {{{*/
     
    281274}
    282275/*}}}*/
    283 
    284276
    285277/*Load virtual functions definitions:*/
     
    301293        this->parameters=parametersin;
    302294
     295}
     296/*}}}*/
     297/*FUNCTION Riftfront::IsPenalty{{{*/
     298bool Riftfront::IsPenalty(void){
     299        return true;
    303300}
    304301/*}}}*/
     
    372369}
    373370/*}}}*/
     371/*FUNCTION Riftfront::GetNodesSidList{{{*/
     372void Riftfront::GetNodesSidList(int* sidlist){
     373
     374        _assert_(sidlist);
     375        _assert_(nodes);
     376
     377        for(int i=0;i<NUMVERTICES;i++) sidlist[i]=nodes[i]->Sid();
     378}
     379/*}}}*/
     380/*FUNCTION Riftfront::GetNumberOfNodes{{{*/
     381int Riftfront::GetNumberOfNodes(void){
     382
     383        return NUMVERTICES;
     384}
     385/*}}}*/
    374386/*FUNCTION Riftfront::InAnalysis{{{*/
    375387bool Riftfront::InAnalysis(int in_analysis_type){
     
    378390}
    379391/*}}}*/
     392/*FUNCTION Riftfront::SetwiseNodeConnectivity{{{*/
     393void Riftfront::SetwiseNodeConnectivity(int* pd_nz,int* po_nz,Node* node,bool* flags,int set1_enum,int set2_enum){
     394
     395        /*Output */
     396        int d_nz = 0;
     397        int o_nz = 0;
     398
     399        /*Loop over all nodes*/
     400        for(int i=0;i<NUMVERTICES;i++){
     401
     402                if(!flags[this->nodes[i]->Sid()]){
     403
     404                        /*flag current node so that no other element processes it*/
     405                        flags[this->nodes[i]->Sid()]=true;
     406
     407                        /*if node is clone, we have an off-diagonal non-zero, else it is a diagonal non-zero*/
     408                        switch(set2_enum){
     409                                case FsetEnum:
     410                                        if(nodes[i]->indexing.fsize){
     411                                                if(this->nodes[i]->IsClone())
     412                                                 o_nz += 1;
     413                                                else
     414                                                 d_nz += 1;
     415                                        }
     416                                        break;
     417                                case GsetEnum:
     418                                        if(nodes[i]->indexing.gsize){
     419                                                if(this->nodes[i]->IsClone())
     420                                                 o_nz += 1;
     421                                                else
     422                                                 d_nz += 1;
     423                                        }
     424                                        break;
     425                                case SsetEnum:
     426                                        if(nodes[i]->indexing.ssize){
     427                                                if(this->nodes[i]->IsClone())
     428                                                 o_nz += 1;
     429                                                else
     430                                                 d_nz += 1;
     431                                        }
     432                                        break;
     433                                default: _error_("not supported");
     434                        }
     435                }
     436        }
     437
     438        /*Assign output pointers: */
     439        *pd_nz=d_nz;
     440        *po_nz=o_nz;
     441}
     442/*}}}*/
    380443
    381444/*Riftfront numerics*/
     
    384447
    385448        const int   numdof = NDOF2*NUMVERTICES;
    386         int         i,j;
    387449        int         dofs[1]             = {0};
    388         IssmDouble      Ke_gg[4][4];
    389         IssmDouble      thickness;
    390         IssmDouble      h[2];
    391         IssmDouble      penalty_offset;
    392         IssmDouble      friction;
     450        IssmDouble  thickness;
     451        IssmDouble  h[2];
     452        IssmDouble  penalty_offset;
     453        IssmDouble  friction;
    393454
    394455        /*Objects: */
     
    466527ElementVector* Riftfront::PenaltyCreatePVectorDiagnosticHoriz(IssmDouble kmax){
    467528
    468         const int   numdof = NDOF2*NUMVERTICES;
    469         int         i,j;
    470         IssmDouble      rho_ice;
    471         IssmDouble      rho_water;
    472         IssmDouble      gravity;
    473         IssmDouble      thickness;
    474         IssmDouble      h[2];
    475         IssmDouble      bed;
    476         IssmDouble      b[2];
    477         IssmDouble      pressure;
    478         IssmDouble      pressure_litho;
    479         IssmDouble      pressure_air;
    480         IssmDouble      pressure_melange;
    481         IssmDouble      pressure_water;
    482         int         fill;
    483         bool        shelf;
     529        const int  numdof = NDOF2*NUMVERTICES;
     530        int        j;
     531        IssmDouble rho_ice;
     532        IssmDouble rho_water;
     533        IssmDouble gravity;
     534        IssmDouble thickness;
     535        IssmDouble h[2];
     536        IssmDouble bed;
     537        IssmDouble b[2];
     538        IssmDouble pressure;
     539        IssmDouble pressure_litho;
     540        IssmDouble pressure_air;
     541        IssmDouble pressure_melange;
     542        IssmDouble pressure_water;
     543        int        fill;
     544        bool       shelf;
    484545
    485546        /*Objects: */
    486         Tria       *tria1              = NULL;
    487         Tria       *tria2              = NULL;
     547        Tria *tria1 = NULL;
     548        Tria *tria2 = NULL;
    488549
    489550        /*enum of element? */
     
    569630
    570631        const int   numnodes        = 2;
    571         IssmDouble      max_penetration;
    572632        IssmDouble      penetration;
    573633        int         activate;
    574         int         found;
    575634        int         unstable;
    576635        IssmDouble      vx1;
     
    602661                if(this->state==OpenEnum)this->active=0;
    603662                if(this->state==ClosedEnum)this->active=1;
    604                
     663
    605664                /*this segment is like frozen, no instability here: */
    606665                *punstable=0;
    607666                return 1;
    608667        }
    609 
    610668
    611669        /*recover parameters: */
     
    674732int   Riftfront::IsMaterialStable(void){
    675733
    676         int found=0;
    677734        IssmDouble converged=0;
    678735
     
    693750
    694751        const int     numnodes=2;
    695         IssmDouble        max_penetration;
    696752        IssmDouble        penetration=0;
    697         int           found;
    698753        IssmDouble      vx1;
    699754        IssmDouble      vy1;
     
    729784        /*If we are zigzag locked, same thing: */
    730785        if(this->counter>this->penalty_lock)penetration=-1;
    731        
     786
    732787        /*assign output pointer: */
    733788        *ppenetration=penetration;
     
    744799
    745800        IssmDouble    penetration;
    746         int       found;
    747801
    748802        /*Objects: */
     
    768822        /*Now, we return penetration only if we are active!: */
    769823        if(this->active==0)penetration=0;
    770        
     824
    771825        /*assign output pointer: */
    772826        *ppenetration=penetration;
     
    777831int   Riftfront::PotentialUnstableConstraint(int* punstable){
    778832
    779 
    780833        const int   numnodes        = 2;
    781         IssmDouble      max_penetration;
    782         IssmDouble      penetration;
    783         int         activate;
     834        IssmDouble  penetration;
    784835        int         unstable;
    785         int         found;
    786         IssmDouble      vx1;
    787         IssmDouble      vy1;
    788         IssmDouble      vx2;
    789         IssmDouble      vy2;
     836        IssmDouble  vx1;
     837        IssmDouble  vy1;
     838        IssmDouble  vx2;
     839        IssmDouble  vy2;
    790840
    791841        /*Objects: */
    792         Tria       *tria1           = NULL;
    793         Tria       *tria2           = NULL;
     842        Tria       *tria1 = NULL;
     843        Tria       *tria2 = NULL;
    794844
    795845        /*enum of element? */
     
    833883        IssmDouble      penetration;
    834884        int         unstable;
    835         int         found;
    836885        IssmDouble      vx1;
    837886        IssmDouble      vy1;
  • issm/trunk/src/c/classes/objects/Loads/Riftfront.h

    r13395 r13975  
    2525                Hook* helements;
    2626                Hook* hmatpar;
    27                
     27
    2828                /*Corresponding fields*/
    2929                Matpar   *matpar;
     
    3232
    3333                /*computational: */
    34                 int      penalty_lock;
    35                 bool     active;
    36                 bool     frozen;
    37                 int      counter;
    38                 bool     prestable;
    39                 bool     material_converged;
    40                 IssmDouble   normal[2];
    41                 IssmDouble   length;
    42                 IssmDouble   fraction;
    43                 int      state;
    44                
    45                 Parameters* parameters; //pointer to solution parameters
    46                 Inputs*  inputs;
     34                int         penalty_lock;
     35                bool        active;
     36                bool        frozen;
     37                int         counter;
     38                bool        prestable;
     39                bool        material_converged;
     40                IssmDouble  normal[2];
     41                IssmDouble  length;
     42                IssmDouble  fraction;
     43                int         state;
    4744
     45                Parameters *parameters;           //pointer to solution parameters
     46                Inputs     *inputs;
    4847
    4948                /*Riftfrontconstructors,destructors: {{{*/
     
    5655                void  DeepEcho();
    5756                int   Id();
    58                 int   MyRank();
    5957                int   ObjectEnum();
    6058                Object* copy();
     
    8078                void  CreatePVector(Vector<IssmDouble>* pf);
    8179                void  CreateJacobianMatrix(Matrix<IssmDouble>* Jff){_error_("Not implemented yet");};
     80                void  GetNodesSidList(int* sidlist);
     81                int   GetNumberOfNodes(void);
     82                bool  IsPenalty(void);
    8283                void  PenaltyCreateJacobianMatrix(Matrix<IssmDouble>* Jff,IssmDouble kmax){_error_("Not implemented yet");};
    8384                void  PenaltyCreateKMatrix(Matrix<IssmDouble>* Kff, Matrix<IssmDouble>* kfs, IssmDouble kmax);
    8485                void  PenaltyCreatePVector(Vector<IssmDouble>* pf, IssmDouble kmax);
     86                void  SetwiseNodeConnectivity(int* d_nz,int* o_nz,Node* node,bool* flags,int set1_enum,int set2_enum);
    8587                bool  InAnalysis(int analysis_type);
    8688                /*}}}*/
  • issm/trunk/src/c/classes/objects/Materials/Matdamageice.cpp

    r13395 r13975  
    1515#include "../../../shared/shared.h"
    1616#include "../../../include/include.h"
    17                
     17
    1818/*Matdamageice constructors and destructor*/
    1919/*FUNCTION Matdamageice::Matdamageice(){{{*/
     
    2828
    2929        /*Intermediaries:*/
    30         int    i;
    3130        int    matice_eid;
    3231
     
    8281int    Matdamageice::Id(void){ return mid; }
    8382/*}}}*/
    84 /*FUNCTION Matdamageice::MyRank {{{*/
    85 int    Matdamageice::MyRank(void){
    86         extern int my_rank;
    87         return my_rank;
    88 }
    89 /*}}}*/
    9083/*FUNCTION Matdamageice::ObjectEnum{{{*/
    9184int Matdamageice::ObjectEnum(void){
     
    210203                        /*Prepare index list*/
    211204                        int doflist1[3];
    212                         for(int i=0;i<3;i++) doflist1[i]=((Tria*)element)->nodes[i]->GetVertexDof();
     205                        for(int i=0;i<3;i++) doflist1[i]=((Tria*)element)->nodes[i]->GetVertexPid();
    213206
    214207                        /*Get input (either in element or material)*/
     
    305298         * return g, initial viscosity.
    306299         */
    307        
     300
    308301        /*output: */
    309302        IssmDouble viscosity3d;
     
    347340                        else{
    348341                                e=(n-1)/2/n;
    349                        
     342
    350343                                viscosity3d=B/(2*pow(A,e));
    351344                        }
     
    376369         * return g, initial viscosity.
    377370         */
    378        
     371
    379372        /*output: */
    380373        IssmDouble viscosity3d;
     
    393386        Z=GetZ();
    394387        B=Z*GetB();
    395        
     388
    396389        if (n==1){
    397390                /*Viscous behaviour! viscosity3d=B: */
     
    446439         * return mu20, initial viscosity.
    447440         */
    448        
     441
    449442        /*output: */
    450443        IssmDouble viscosity_complement;
     
    474467                else{
    475468                        e=(n-1)/(2*n);
    476                
     469
    477470                        viscosity_complement=1/(2*pow(A,e));
    478471                }
     
    486479        _assert_(n>0);
    487480        _assert_(viscosity_complement>0);
    488                
     481
    489482        /*Return: */
    490483        *pviscosity_complement=viscosity_complement;
     
    502495         * return mu20, initial viscosity.
    503496         */
    504        
     497
    505498        /*output: */
    506499        IssmDouble viscosity_complement;
     
    530523                else{
    531524                        e=(n-1)/(2*n);
    532                
     525
    533526                        viscosity_complement=B/(2*pow(A,e));
    534527                }
     
    542535        _assert_(n>0);
    543536        _assert_(viscosity_complement>0);
    544                
     537
    545538        /*Return: */
    546539        *pviscosity_complement=viscosity_complement;
     
    589582
    590583        /*input strain rate: */
    591         IssmDouble exx,eyy,exy,exz;
     584        IssmDouble exx,eyy,exy;
    592585
    593586        /*Get visocisty and n*/
     
    640633                                case TriaEnum: {
    641634                                        IssmDouble values[3];
    642                                         for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetVertexDof()];
     635                                        for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetVertexPid()];
    643636                                        this->inputs->AddInput(new TriaP1Input(name,values));
    644637                                        return;
     
    682675                                case TriaEnum: {
    683676                                        IssmDouble values[3];
    684                                         for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetSidList()]; //use sid list, to index into serial oriented vector
     677                                        for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetVertexSid()]; //use sid list, to index into serial oriented vector
    685678                                        this->inputs->AddInput(new TriaP1Input(name,values));
    686679                                        /*Special case for rheology B in 2D: Pourave land for this solution{{{*/
     
    706699                default: _error_("type " << type << " (" << EnumToStringx(type) << ") not implemented yet");
    707700        }
    708 
    709 
    710701
    711702}
  • issm/trunk/src/c/classes/objects/Materials/Matdamageice.h

    r13395 r13975  
    2828                void  DeepEcho();
    2929                int   Id();
    30                 int   MyRank();
    3130                int   ObjectEnum();
    3231                Object* copy();
  • issm/trunk/src/c/classes/objects/Materials/Material.h

    r13395 r13975  
    22 * \brief abstract class for Material object
    33 */
    4 
    54
    65#ifndef _MATERIAL_H_
  • issm/trunk/src/c/classes/objects/Materials/Matice.cpp

    r13395 r13975  
    1515#include "../../../shared/shared.h"
    1616#include "../../../include/include.h"
    17                
     17
    1818/*Matice constructors and destructor*/
    1919/*FUNCTION Matice::Matice(){{{*/
     
    2828
    2929        /*Intermediaries:*/
    30         int    i;
    3130        int    matice_eid;
    3231
     
    8281int    Matice::Id(void){ return mid; }
    8382/*}}}*/
    84 /*FUNCTION Matice::MyRank {{{*/
    85 int    Matice::MyRank(void){
    86         extern int my_rank;
    87         return my_rank;
    88 }
    89 /*}}}*/
    9083/*FUNCTION Matice::ObjectEnum{{{*/
    9184int Matice::ObjectEnum(void){
     
    190183                        /*Prepare index list*/
    191184                        int doflist1[3];
    192                         for(int i=0;i<3;i++) doflist1[i]=((Tria*)element)->nodes[i]->GetVertexDof();
     185                        for(int i=0;i<3;i++) doflist1[i]=((Tria*)element)->nodes[i]->GetVertexPid();
    193186
    194187                        /*Get input (either in element or material)*/
     
    283276         * return g, initial viscosity.
    284277         */
    285        
     278
    286279        /*output: */
    287280        IssmDouble viscosity3d;
     
    324317                        else{
    325318                                e=(n-1)/2/n;
    326                        
     319
    327320                                viscosity3d=B/(2*pow(A,e));
    328321                        }
     
    353346         * return g, initial viscosity.
    354347         */
    355        
     348
    356349        /*output: */
    357350        IssmDouble viscosity3d;
     
    369362        B=GetB();
    370363        n=GetN();
    371        
     364
    372365        if (n==1){
    373366                /*Viscous behaviour! viscosity3d=B: */
     
    422415         * return mu20, initial viscosity.
    423416         */
    424        
     417
    425418        /*output: */
    426419        IssmDouble viscosity_complement;
     
    450443                else{
    451444                        e=(n-1)/(2*n);
    452                
     445
    453446                        viscosity_complement=1/(2*pow(A,e));
    454447                }
     
    462455        _assert_(n>0);
    463456        _assert_(viscosity_complement>0);
    464                
     457
    465458        /*Return: */
    466459        *pviscosity_complement=viscosity_complement;
     
    509502
    510503        /*input strain rate: */
    511         IssmDouble exx,eyy,exy,exz;
     504        IssmDouble exx,eyy,exy;
    512505
    513506        /*Get visocisty and n*/
     
    560553                                case TriaEnum: {
    561554                                        IssmDouble values[3];
    562                                         for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetVertexDof()];
     555                                        for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetVertexPid()];
    563556                                        this->inputs->AddInput(new TriaP1Input(name,values));
    564557                                        return;
     
    602595                                case TriaEnum: {
    603596                                        IssmDouble values[3];
    604                                         for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetSidList()]; //use sid list, to index into serial oriented vector
     597                                        for (int i=0;i<3;i++) values[i]=vector[((Tria*)element)->nodes[i]->GetVertexSid()]; //index into serial oriented vector
    605598                                        this->inputs->AddInput(new TriaP1Input(name,values));
    606599                                        /*Special case for rheology B in 2D: Pourave land for this solution{{{*/
     
    627620        }
    628621
    629 
    630 
    631622}
    632623/*}}}*/
  • issm/trunk/src/c/classes/objects/Materials/Matice.h

    r13395 r13975  
    1515
    1616        private:
    17                 int        mid;
    18                 Hook* helement;
     17                int   mid;
     18                Hook *helement;
    1919
    2020        public:
     
    2828                void  DeepEcho();
    2929                int   Id();
    30                 int   MyRank();
    3130                int   ObjectEnum();
    3231                Object* copy();
  • issm/trunk/src/c/classes/objects/Materials/Matpar.cpp

    r13395 r13975  
    1515#include "../../../include/include.h"
    1616#include "../../../EnumDefinitions/EnumDefinitions.h"
    17                
     17
    1818/*Matpar constructors and destructor*/
    1919/*FUNCTION Matpar::Matpar() {{{*/
     
    3939        iomodel->Constant(&this->thermal_exchange_velocity,MaterialsThermalExchangeVelocityEnum);
    4040        iomodel->Constant(&this->g,ConstantsGEnum);
    41        
     41
    4242        iomodel->Constant(&this->hydro_CR,HydrologyCREnum);
    4343        iomodel->Constant(&this->kn,HydrologyKnEnum);
     
    8585int    Matpar::Id(void){ return mid; }
    8686/*}}}*/
    87 /*FUNCTION Matpar::MyRank {{{*/
    88 int    Matpar::MyRank(void){
    89         extern int my_rank;
    90         return my_rank;
    91 }
    92 /*}}}*/
    9387/*FUNCTION Matpar::ObjectEnum{{{*/
    9488int Matpar::ObjectEnum(void){
     
    250244/*FUNCTION Matpar::GetRhoIce {{{*/
    251245IssmDouble Matpar::GetRhoIce(){
    252        
     246
    253247        return rho_ice;
    254248}
     
    329323        /*Ouput*/
    330324        IssmDouble temperature,waterfraction;
    331        
     325
    332326        if(enthalpy<PureIceEnthalpy(pressure)){
    333327                temperature=referencetemperature+enthalpy/heatcapacity;
     
    349343        /*Ouput*/
    350344        IssmDouble enthalpy;
    351        
     345
    352346        if(temperature<TMeltingPoint(pressure)){
    353347                enthalpy=heatcapacity*(temperature-referencetemperature);
  • issm/trunk/src/c/classes/objects/Materials/Matpar.h

    r13395 r13975  
    4343
    4444                /*Object virtual functions definitions:{{{ */
    45                 void  Echo();
    46                 void  DeepEcho();
    47                 int   Id();
    48                 int   MyRank();
    49                 int   ObjectEnum();
    50                 Object* copy();
     45                void    Echo();
     46                void    DeepEcho();
     47                int     Id();
     48                int     ObjectEnum();
     49                Object *copy();
    5150                /*}}}*/
    5251                /*Update virtual functions resolution: {{{*/
  • issm/trunk/src/c/classes/objects/Node.cpp

    r13395 r13975  
    5858        this->inputs=new Inputs();
    5959        if (iomodel->Data(MeshVertexonbedEnum))
    60          this->inputs->AddInput(new BoolInput(MeshVertexonbedEnum,reCast<IssmBool>(iomodel->Data(MeshVertexonbedEnum)[io_index])));
     60         this->inputs->AddInput(new BoolInput(MeshVertexonbedEnum,reCast<bool>(iomodel->Data(MeshVertexonbedEnum)[io_index])));
    6161        if (iomodel->Data(MeshVertexonsurfaceEnum))
    62          this->inputs->AddInput(new BoolInput(MeshVertexonsurfaceEnum,reCast<IssmBool>(iomodel->Data(MeshVertexonsurfaceEnum)[io_index])));
     62         this->inputs->AddInput(new BoolInput(MeshVertexonsurfaceEnum,reCast<bool>(iomodel->Data(MeshVertexonsurfaceEnum)[io_index])));
    6363        if (iomodel->Data(MaskVertexonfloatingiceEnum))
    64          this->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,reCast<IssmBool>(iomodel->Data(MaskVertexonfloatingiceEnum)[io_index])));
     64         this->inputs->AddInput(new BoolInput(MaskVertexonfloatingiceEnum,reCast<bool>(iomodel->Data(MaskVertexonfloatingiceEnum)[io_index])));
    6565        if (iomodel->Data(MaskVertexongroundediceEnum))
    66           this->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,reCast<IssmBool>(iomodel->Data(MaskVertexongroundediceEnum)[io_index])));
     66          this->inputs->AddInput(new BoolInput(MaskVertexongroundediceEnum,reCast<bool>(iomodel->Data(MaskVertexongroundediceEnum)[io_index])));
    6767        if (analysis_type==DiagnosticHorizAnalysisEnum)
    6868         this->inputs->AddInput(new IntInput(ApproximationEnum,reCast<IssmInt>(iomodel->Data(FlowequationVertexEquationEnum)[io_index])));
     
    7171        /*spc all nodes on water*/
    7272        if (!iomodel->Data(MaskVertexonwaterEnum)) _error_("iomodel->nodeonwater is NULL");
    73         if (reCast<IssmBool>(iomodel->Data(MaskVertexonwaterEnum)[io_index])){
     73        if (reCast<bool>(iomodel->Data(MaskVertexonwaterEnum)[io_index])){
    7474                for(k=1;k<=gsize;k++){
    7575                        this->FreezeDof(k);
     
    137137                        /*On a 3d mesh, we may have collapsed elements, hence dead nodes. Freeze them out: */
    138138                        _assert_(iomodel->Data(MeshVertexonbedEnum));
    139                         if (!(reCast<IssmBool>(iomodel->Data(MeshVertexonbedEnum)[io_index]))){
     139                        if (!(reCast<bool>(iomodel->Data(MeshVertexonbedEnum)[io_index]))){
    140140                                for(k=1;k<=gsize;k++){
    141141                                        this->FreezeDof(k);
     
    166166        _printLine_("   hvertex:     not displayed");
    167167        _printLine_("   inputs:      " << inputs);
    168 
    169168
    170169}
     
    182181        _printLine_("   inputs");
    183182
    184 
    185183}
    186184/*}}}*/
    187185/*FUNCTION Node::Id{{{*/
    188186int    Node::Id(void){ return id; }
    189 /*}}}*/
    190 /*FUNCTION Node::MyRank{{{*/
    191 int    Node::MyRank(void){
    192         extern int my_rank;
    193 
    194         return my_rank;
    195 }
    196187/*}}}*/
    197188/*FUNCTION Node::ObjectEnum{{{*/
     
    234225
    235226} /*}}}*/
    236 /*FUNCTION Node::GetDofList1{{{*/
    237 int  Node::GetDofList1(void){
    238 
    239         Vertex* vertex=NULL;
    240 
    241         vertex=(Vertex*)this->hvertex->delivers();
    242 
    243         return vertex->dof;
    244 }
    245 /*}}}*/
    246227/*FUNCTION Node::GetDofList{{{*/
    247228void  Node::GetDofList(int* outdoflist,int approximation_enum,int setenum){
     
    249230        int count=0;
    250231        int count2=0;
    251                
     232
    252233        if(approximation_enum==NoneApproximationEnum){
    253234                if(setenum==GsetEnum)for(i=0;i<this->indexing.gsize;i++) outdoflist[i]=indexing.gdoflist[i];
     
    306287}
    307288/*}}}*/
    308 /*FUNCTION Node::GetSidList{{{*/
    309 int  Node::GetSidList(void){
    310 
    311         Vertex* vertex=NULL;
    312 
    313         vertex=(Vertex*)this->hvertex->delivers();
    314 
    315         return vertex->sid;
    316 }
    317 /*}}}*/
    318289/*FUNCTION Node::GetLocalDofList{{{*/
    319290void  Node::GetLocalDofList(int* outdoflist,int approximation_enum,int setenum){
     
    321292        int count=0;
    322293        int count2=0;
    323                
     294
    324295        if(approximation_enum==NoneApproximationEnum){
    325296                if(setenum==GsetEnum)for(i=0;i<this->indexing.gsize;i++) outdoflist[i]=i;
     
    427398}
    428399/*}}}*/
    429 /*FUNCTION Node::GetVertexDof {{{*/
    430 int   Node::GetVertexDof(void){
     400/*FUNCTION Node::GetVertexPid{{{*/
     401int   Node::GetVertexPid(void){
    431402
    432403        Vertex*  vertex=NULL;
    433404
    434405        vertex=(Vertex*)hvertex->delivers();
    435         return vertex->dof;
     406        return vertex->pid;
     407}
     408/*}}}*/
     409/*FUNCTION Node::GetVertexSid{{{*/
     410int  Node::GetVertexSid(void){
     411
     412        Vertex* vertex=NULL;
     413
     414        vertex=(Vertex*)this->hvertex->delivers();
     415
     416        return vertex->sid;
    436417}
    437418/*}}}*/
     
    446427/*}}}*/
    447428#endif
    448 /*FUNCTION Node::SetVertexDof {{{*/
    449 void   Node::SetVertexDof(int in_dof){
    450 
    451         Vertex*  vertex=NULL;
    452 
    453         vertex=(Vertex*)hvertex->delivers();
    454         vertex->dof=in_dof;
    455 
    456 }
    457 /*}}}*/
    458429/*FUNCTION Node::InAnalysis{{{*/
    459430bool Node::InAnalysis(int in_analysis_type){
     
    467438void  Node::ApplyConstraint(int dof,IssmDouble value){
    468439
    469         int index;
    470 
    471440        /*Dof should be added in the s set, describing which
    472441         * dofs are constrained to a certain value (dirichlet boundary condition*/
     
    495464                /*g set: */
    496465                pv_g->SetValue(indexing.gdoflist[i],gvalue,INS_VAL);
    497                
     466
    498467                /*f set: */
    499468                value=(IssmDouble)this->indexing.f_set[i];
     
    505474
    506475        }
    507 
    508476
    509477}
     
    527495                        }
    528496                }
    529                
     497
    530498                /*Add values into constraint vector: */
    531499                ys->SetValues(this->indexing.ssize,this->indexing.sdoflist,values,INS_VAL);
     
    535503        xDelete<IssmDouble>(values);
    536504
    537 
    538505}
    539506/*}}}*/
     
    560527/*FUNCTION Node::FreezeDof{{{*/
    561528void  Node::FreezeDof(int dof){
    562        
     529
    563530        DofInSSet(dof-1); //with 0 displacement for this dof.
    564531
     
    589556        /*Get number of degrees of freedom in a node, for a certain set (g,f or s-set)
    590557         *and for a certain approximation type: */
    591        
     558
    592559        int i;
    593560        int numdofs=0;
     
    666633/*FUNCTION Node::IsClone {{{*/
    667634int   Node::IsClone(){
    668        
     635
    669636        return indexing.clone;
    670637
     
    695662/*FUNCTION Node::IsFloating {{{*/
    696663int   Node::IsFloating(){
    697        
     664
    698665        bool onshelf;
    699666
     
    887854/*}}}*/
    888855
    889 /* DofObject routines:*/
     856/* indexing routines:*/
    890857/*FUNCTION Node::DistributeDofs{{{*/
    891858void  Node::DistributeDofs(int* pdofcount,int setenum){
    892859
    893860        int i;
    894         extern int my_rank;
    895861        int dofcount;
    896862
     
    900866        if(setenum==FsetEnum) this->indexing.InitSet(setenum);
    901867        if(setenum==SsetEnum) this->indexing.InitSet(setenum);
    902        
    903                
     868
    904869        /*For clone nodfs, don't distribute dofs, we will get them from another cpu in UpdateCloneDofs!*/
    905870        if(indexing.clone){
     
    908873
    909874        /*This node should distribute dofs for setenum set (eg, f_set or s_set), go ahead: */
    910 
    911875        if(setenum==GsetEnum){
    912876                for(i=0;i<this->indexing.gsize;i++){
     
    929893        else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
    930894
    931 
    932895        /*Assign output pointers: */
    933896        *pdofcount=dofcount;
    934 
    935 }
    936 /*}}}*/
    937 /*FUNCTION Node::Off_setDofs{{{*/
     897}
     898/*}}}*/
     899/*FUNCTION Node::OffsetDofs{{{*/
    938900void  Node::OffsetDofs(int dofcount,int setenum){
    939        
     901
    940902        int i;
    941         extern int my_rank;
    942        
     903
    943904        if(indexing.clone){
    944905                /*This node is a clone, don't off_set the dofs!: */
     
    963924
    964925        int j;
    965         extern int my_rank;
    966        
     926
    967927        /*Are we a clone? : */
    968         if(indexing.clone)return;
     928        if(indexing.clone) return;
    969929
    970930        /*Ok, we are not a clone, just plug our dofs into truedofs: */
    971         if(setenum==GsetEnum)for(j=0;j<this->indexing.gsize;j++)  *(truedofs+ncols*sid+j)=indexing.gdoflist[j];
    972         else if(setenum==FsetEnum)for(j=0;j<this->indexing.fsize;j++)  *(truedofs+ncols*sid+j)=indexing.fdoflist[j];
    973         else if(setenum==SsetEnum)for(j=0;j<this->indexing.ssize;j++)  *(truedofs+ncols*sid+j)=indexing.sdoflist[j];
    974         else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
     931        switch(setenum){
     932                case GsetEnum:
     933                        for(j=0;j<this->indexing.gsize;j++) truedofs[ncols*sid+j]=indexing.gdoflist[j];
     934                        break;
     935                case FsetEnum:
     936                        for(j=0;j<this->indexing.fsize;j++) truedofs[ncols*sid+j]=indexing.fdoflist[j];
     937                        break;
     938                case SsetEnum:
     939                        for(j=0;j<this->indexing.ssize;j++) truedofs[ncols*sid+j]=indexing.sdoflist[j];
     940                        break;
     941                default:
     942                        _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
     943        }
    975944
    976945}
     
    980949
    981950        int j;
    982         extern int my_rank;
    983        
     951
    984952        /*If we are not a clone, don't update, we already have dofs!: */
    985         if(indexing.clone==0)return;
    986 
     953        if(!indexing.clone)return;
    987954
    988955        /*Ok, we are a clone node, but we did not create the dofs for this node.
    989          *      * Therefore, our doflist is garbage right now. Go pick it up in the alltruedofs: */
    990         if(setenum==GsetEnum)for(j=0;j<this->indexing.gsize;j++) indexing.gdoflist[j]=*(alltruedofs+ncols*sid+j);
    991         else if(setenum==FsetEnum)for(j=0;j<this->indexing.fsize;j++) indexing.fdoflist[j]=*(alltruedofs+ncols*sid+j);
    992         else if(setenum==SsetEnum)for(j=0;j<this->indexing.ssize;j++) indexing.sdoflist[j]=*(alltruedofs+ncols*sid+j);
    993         else _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
    994 
     956         *Therefore, our doflist is garbage right now. Go pick it up in the alltruedofs: */
     957        switch(setenum){
     958                case GsetEnum:
     959                        for(j=0;j<this->indexing.gsize;j++) indexing.gdoflist[j]=alltruedofs[ncols*sid+j];
     960                        break;
     961                case FsetEnum:
     962                        for(j=0;j<this->indexing.fsize;j++) indexing.fdoflist[j]=alltruedofs[ncols*sid+j];
     963                        break;
     964                case SsetEnum:
     965                        for(j=0;j<this->indexing.ssize;j++) indexing.sdoflist[j]=alltruedofs[ncols*sid+j];
     966                        break;
     967                default:
     968                        _error_("set of enum type " << EnumToStringx(setenum) << " not supported yet!");
     969        }
    995970}
    996971/*}}}*/
     
    998973void  Node::SetClone(int* minranks){
    999974
    1000         extern int my_rank;
     975        int my_rank;
     976
     977        /*recover my_rank:*/
     978        my_rank=IssmComm::GetRank();
    1001979
    1002980        if (minranks[sid]==my_rank){
    1003                 indexing.clone=0;
     981                indexing.clone=false;
    1004982        }
    1005983        else{
    1006984                /*!there is a cpu with lower rank that has the same node,
    1007985                therefore, I am a clone*/
    1008                 indexing.clone=1;       
    1009         }
    1010 
    1011 }
    1012 /*}}}*/
     986                indexing.clone=true;   
     987        }
     988}
     989/*}}}*/
  • issm/trunk/src/c/classes/objects/Node.h

    r13395 r13975  
    2525        public:
    2626
    27                 int         id;  //unique arbitrary id.
    28                 int     sid; //sid for "serial" id, ie the rank of this node in the nodes dataset, if the dataset was serial on 1 cpu.
    29                                
    30                 DofIndexing    indexing;
    31                 Hook*          hvertex;
    32                 Inputs*        inputs; //properties of this node
    33                 int            analysis_type;
    34                 IssmDouble         coord_system[3][3];
     27                int id;    //unique arbitrary id.
     28                int sid;   //"serial" id (rank of this node if the dataset was serial on 1 cpu)
     29
     30                DofIndexing  indexing;
     31                Hook        *hvertex;
     32                Inputs      *inputs;              //properties of this node
     33                int          analysis_type;
     34                IssmDouble   coord_system[3][3];
    3535
    3636                /*Node constructors, destructors {{{*/
     
    4040                /*}}}*/
    4141                /*Object virtual functions definitions:{{{ */
    42                 void  Echo();
    43                 void  DeepEcho();
    44                 int   Id();
    45                 int   MyRank();
    46                 int   ObjectEnum();
    47                 Object* copy(){_error_("Not implemented yet (similar to Elements)");};
     42                void    Echo();
     43                void    DeepEcho();
     44                int     Id();
     45                int     ObjectEnum();
     46                Object *copy()        {_error_("Not implemented yet (similar to Elements)"); };
    4847                /*}}}*/
    4948                /*Update virtual functions definitions: {{{*/
    50                
    5149                void  InputUpdateFromVector(IssmDouble* vector, int name, int type);
    5250                void  InputUpdateFromVector(int* vector, int name, int type);
     
    6765                void   SetCurrentConfiguration(DataSet* nodes,Vertices* vertices);
    6866                int    Sid(void);
    69                 int    GetVertexDof(void);
    70                 int    GetVertexId(void);
    7167#ifdef _HAVE_DIAGNOSTIC_
    7268                void   GetCoordinateSystem(IssmDouble* coord_system_out);
    7369#endif
    74                 void   SetVertexDof(int in_dof);
    7570                bool   InAnalysis(int analysis_type);
    7671                int    GetApproximation();
     
    8681                void   GetDofList(int* poutdoflist,int approximation_enum,int setenum);
    8782                void   GetLocalDofList(int* poutdoflist,int approximation_enum,int setenum);
    88                 int    GetDofList1(void);
    89                 int    GetSidList(void);
     83                int    GetVertexId(void);
     84                int    GetVertexPid(void);
     85                int    GetVertexSid(void);
    9086                IssmDouble GetX();
    9187                IssmDouble GetY();
     
    10096                void   VecMerge(Vector<IssmDouble>* ug, IssmDouble* vector_serial,int setenum);
    10197                void   VecReduce(Vector<IssmDouble>* vector, IssmDouble* ug_serial,int setnum);
    102                
    103                 /*}}}*/
    104                 /*Dof Object routines {{{*/
    10598                void  DistributeDofs(int* pdofcount,int setenum);
    10699                void  OffsetDofs(int dofcount,int setenum);
  • issm/trunk/src/c/classes/objects/Object.h

    r13395 r13975  
    77 * DataSet.
    88 */
    9 
    109
    1110#ifndef _OBJECT_H_
     
    2019                virtual void  DeepEcho()=0;
    2120                virtual int   Id()=0;
    22                 virtual int   MyRank()=0;
    2321                virtual int   ObjectEnum()=0;
    2422                virtual Object* copy()=0;
  • issm/trunk/src/c/classes/objects/Options/GenericOption.h

    r13395 r13975  
    2929        public:
    3030
    31                 char* name;
    32                 OptionType value;
     31                char       *name;
     32                OptionType  value;
    3333
    34                 int   numel; //in case OptionType is an array
    35                 int   ndims; //in case OptionType is a multi-dimensional array: */
    36                 intsize;
     34                int         numel;  //in case OptionType is an array
     35                int         ndims;  //in case OptionType is a multi-dimensional array: */
     36                int        *size;
    3737
    3838                /*GenericOption constructors, destructors*/
     
    4343                        ndims =0;
    4444                        size  =NULL;
    45 
    4645
    4746                } /*}}}*/
     
    8180                } /*}}}*/
    8281                int   Id(){_error_("Not implemented yet");};
    83                 int   MyRank(){_error_("Not implemented yet");};
    8482                int   ObjectEnum(){return GenericOptionEnum;};
    8583                Object* copy(){_error_("Not implemented yet");};
    86                
     84
    8785                /*GenericOption functions: */
    8886                char* Name(){return name;};
     
    9391};
    9492
    95 #ifdef _HAVE_ADOLC_ //We hook off this specific specialization when not running ADOLC, otherwise we get a redeclaration with the next specialization.
     93#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_) //We hook off this specific specialization when not running ADOLC, otherwise we get a redeclaration with the next specialization.
    9694template <> inline void GenericOption<IssmPDouble*>::Get(IssmPDouble** pvalue){ /*{{{*/
    9795
     
    115113template <> inline void GenericOption<char*>::Get(char** pvalue){ /*{{{*/
    116114
    117         char* outstring=NULL;
    118         int   stringsize;
    119 
    120         stringsize=strlen(this->value)+1;
    121         outstring=xNew<char>(stringsize);
     115        int   stringsize=strlen(this->value)+1;
     116        char* outstring=xNew<char>(stringsize);
    122117        xMemCpy<char>(outstring,this->value,stringsize);
    123118
  • issm/trunk/src/c/classes/objects/Options/Option.h

    r13395 r13975  
    1818        public:
    1919
    20                
    21                 /*Option constructors, destructors {{{*/
     20                /*Option constructors, destructors*/
    2221                Option(){};
    2322                ~Option(){};
    24                 /*}}}*/
    25                 /*Object virtual functions definitions:{{{*/
     23
     24                /*Object virtual functions definitions*/
    2625                virtual void  Echo()= 0;
    2726                virtual void  DeepEcho()= 0;
    2827                virtual void  DeepEcho(char  *indent)=0;
    2928                int           Id(){_error_("Not implemented yet"); };
    30                 int           MyRank(){_error_("Not implemented yet"); };
    3129                int           ObjectEnum(){return OptionEnum;              };
    3230                Object       *copy(){_error_("Not implemented yet"); };
    33                 /*}}}*/
    3431
    3532                /*virtual functions: */
     
    4138};
    4239#endif  /* _OPTIONOBJECT_H */
    43 
  • issm/trunk/src/c/classes/objects/Options/OptionUtilities.h

    r13395 r13975  
    2222
    2323#endif  /* _OPTIONUTILITIES_H */
    24 
  • issm/trunk/src/c/classes/objects/Params/BoolParam.cpp

    r13395 r13975  
    2626}
    2727/*}}}*/
    28 /*FUNCTION BoolParam::BoolParam(int enum_type,IssmBool value){{{*/
    29 BoolParam::BoolParam(int in_enum_type,IssmBool in_value){
     28/*FUNCTION BoolParam::BoolParam(int enum_type,bool value){{{*/
     29BoolParam::BoolParam(int in_enum_type,bool in_value){
    3030
    3131        enum_type=in_enum_type;
     
    5656int    BoolParam::Id(void){ return -1; }
    5757/*}}}*/
    58 /*FUNCTION BoolParam::MyRank{{{*/
    59 int    BoolParam::MyRank(void){
    60         extern int my_rank;
    61         return my_rank;
    62 }
    63 /*}}}*/
    6458/*FUNCTION BoolParam::ObjectEnum{{{*/
    6559int BoolParam::ObjectEnum(void){
     
    7165/*FUNCTION BoolParam::copy{{{*/
    7266Object* BoolParam::copy() {
    73        
     67
    7468        return new BoolParam(this->enum_type,this->value);
    7569
  • issm/trunk/src/c/classes/objects/Params/BoolParam.h

    r13395 r13975  
    22 *  \brief: header file for triavertexinput object
    33 */
    4 
    54
    65#ifndef _BOOLPARAM_H_
     
    2524                /*just hold 3 values for 3 vertices: */
    2625                int enum_type;
    27                 IssmBool value;
     26                bool value;
    2827
    2928                /*BoolParam constructors, destructors: {{{*/
    3029                BoolParam();
    31                 BoolParam(int enum_type,IssmBool value);
     30                BoolParam(int enum_type,bool value);
    3231                ~BoolParam();
    3332                /*}}}*/
     
    3635                void  DeepEcho();
    3736                int   Id();
    38                 int   MyRank();
    3937                int   ObjectEnum();
    4038                Object* copy();
     
    5654                void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
    5755                void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
     56                void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
    5857
    5958                void  SetValue(bool boolean){this->value=boolean;}
     
    7170                void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
    7271                void  UnitConversion(int direction_enum);
    73                
     72
    7473                void GetParameterName(char**pname);
    7574                /*}}}*/
  • issm/trunk/src/c/classes/objects/Params/DoubleMatArrayParam.cpp

    r13395 r13975  
    7777                xDelete<IssmDouble>(matrix);
    7878        }
    79        
     79
    8080        xDelete<IssmDouble*>(array);
    8181        return;
     
    100100        int m,n;
    101101        IssmDouble* matrix=NULL;
    102        
     102
    103103        _printLine_("DoubleMatArrayParam:");
    104104        _printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
     
    121121int    DoubleMatArrayParam::Id(void){ return -1; }
    122122/*}}}*/
    123 /*FUNCTION DoubleMatArrayParam::MyRank{{{*/
    124 int    DoubleMatArrayParam::MyRank(void){
    125         extern int my_rank;
    126         return my_rank;
    127 }
    128 /*}}}*/
    129123/*FUNCTION DoubleMatArrayParam::ObjectEnum{{{*/
    130124int DoubleMatArrayParam::ObjectEnum(void){
     
    136130/*FUNCTION DoubleMatArrayParam::copy{{{*/
    137131Object* DoubleMatArrayParam::copy() {
    138        
     132
    139133        return new DoubleMatArrayParam(this->enum_type,this->array, this->M, this->mdim_array,this->ndim_array);
    140134
     
    156150        int*     out_ndim_array=NULL;
    157151
    158 
    159152        out_M=this->M;
    160153        if(out_M){
     
    187180        }
    188181
    189 
    190182        /*Assign output pointers:*/
    191183        if(pout_M) *pout_M=out_M;
     
    222214        this->mdim_array=xNew<int>(M);
    223215        this->ndim_array=xNew<int>(M);
    224        
     216
    225217        xMemCpy<int>(this->mdim_array,in_mdim_array,M);
    226218        xMemCpy<int>(this->ndim_array,in_ndim_array,M);
  • issm/trunk/src/c/classes/objects/Params/DoubleMatArrayParam.h

    r13395 r13975  
    22 *  \brief: header file for object holding an array of serial matrices
    33 */
    4 
    54
    65#ifndef _DOUBLEMATARRAYPARAM_H_
     
    2322
    2423        private:
    25                 int      enum_type;
    26                 IssmDouble** array; //array of matrices
    27                 int      M; //size of array
    28                 int*     mdim_array; //m-dimensions of matrices in the array
    29                 int*     ndim_array; //n-dimensions -f matrices in the array
     24                int          enum_type;
     25                IssmDouble **array;        //array of matrices
     26                int          M;            //size of array
     27                int         *mdim_array;  //m-dimensions of matrices in the array
     28                int         *ndim_array;  //n-dimensions -f matrices in the array
    3029
    3130        public:
     
    3938                void  DeepEcho();
    4039                int   Id();
    41                 int   MyRank();
    4240                int   ObjectEnum();
    4341                Object* copy();
     
    5957                void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a Mat");}
    6058                void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << "cannot return a FILE");}
     59                void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
    6160
    6261                void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << "cannot hold a boolean");}
  • issm/trunk/src/c/classes/objects/Params/DoubleMatParam.cpp

    r13395 r13975  
    5858
    5959        int i,j;
    60        
     60
    6161        _printLine_("DoubleMatParam:");
    6262        _printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
     
    7272int    DoubleMatParam::Id(void){ return -1; }
    7373/*}}}*/
    74 /*FUNCTION DoubleMatParam::MyRank{{{*/
    75 int    DoubleMatParam::MyRank(void){
    76         extern int my_rank;
    77         return my_rank;
    78 }
    79 /*}}}*/
    8074/*FUNCTION DoubleMatParam::ObjectEnum{{{*/
    8175int DoubleMatParam::ObjectEnum(void){
     
    8781/*FUNCTION DoubleMatParam::copy{{{*/
    8882Object* DoubleMatParam::copy() {
    89        
     83
    9084        return new DoubleMatParam(this->enum_type,this->value,this->M,this->N);
    9185
  • issm/trunk/src/c/classes/objects/Params/DoubleMatParam.h

    r13395 r13975  
    22 *  \brief: header file for triavertexinput object
    33 */
    4 
    54
    65#ifndef _DOUBLEMATPARAM_H_
     
    2322
    2423        protected:
    25                 int enum_type;
    26                 IssmDouble* value;
    27                 int M;
    28                 int N;
     24                int         enum_type;
     25                IssmDouble *value;
     26                int         M;
     27                int         N;
    2928
    3029        public:
     
    3837                void  DeepEcho();
    3938                int   Id();
    40                 int   MyRank();
    4139                int   ObjectEnum();
    4240                Object* copy();
     
    5856                void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
    5957                void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
     58                void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
    6059
    6160                void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
  • issm/trunk/src/c/classes/objects/Params/DoubleParam.cpp

    r13395 r13975  
    5353int    DoubleParam::Id(void){ return -1; }
    5454/*}}}*/
    55 /*FUNCTION DoubleParam::MyRank{{{*/
    56 int    DoubleParam::MyRank(void){
    57         extern int my_rank;
    58         return my_rank;
    59 }
    60 /*}}}*/
    6155/*FUNCTION DoubleParam::ObjectEnum{{{*/
    6256int DoubleParam::ObjectEnum(void){
     
    6862/*FUNCTION DoubleParam::copy{{{*/
    6963Object* DoubleParam::copy() {
    70        
     64
    7165        return new DoubleParam(this->enum_type,this->value);
    7266
  • issm/trunk/src/c/classes/objects/Params/DoubleParam.h

    r13395 r13975  
    22 *  \brief: header file for triavertexinput object
    33 */
    4 
    54
    65#ifndef _DOUBLEPARAM_H_
     
    2423        private:
    2524                /*just hold 3 values for 3 vertices: */
    26                 int enum_type;
     25                int        enum_type;
    2726                IssmDouble value;
    2827
     
    3736                void  DeepEcho();
    3837                int   Id();
    39                 int   MyRank();
    4038                int   ObjectEnum();
    4139                Object* copy();
     
    5755                void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
    5856                void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
     57                void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
    5958
    6059                void  SetValue(bool boolean){this->value=(IssmDouble)boolean;}
  • issm/trunk/src/c/classes/objects/Params/DoubleTransientMatParam.h

    r13395 r13975  
    22 *  \brief: header file for DoubleTransientMatParam object
    33 */
    4 
    54
    65#ifndef _DOUBLETRANSIENTMATPARAM_H_
  • issm/trunk/src/c/classes/objects/Params/DoubleVecParam.cpp

    r13395 r13975  
    5757
    5858        int i;
    59        
     59
    6060        _printLine_("DoubleVecParam:");
    6161        _printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
     
    6969int    DoubleVecParam::Id(void){ return -1; }
    7070/*}}}*/
    71 /*FUNCTION DoubleVecParam::MyRank{{{*/
    72 int    DoubleVecParam::MyRank(void){
    73         extern int my_rank;
    74         return my_rank;
    75 }
    76 /*}}}*/
    7771/*FUNCTION DoubleVecParam::ObjectEnum{{{*/
    7872int DoubleVecParam::ObjectEnum(void){
     
    8478/*FUNCTION DoubleVecParam::copy{{{*/
    8579Object* DoubleVecParam::copy() {
    86        
     80
    8781        return new DoubleVecParam(this->enum_type,this->values,this->M);
    8882
  • issm/trunk/src/c/classes/objects/Params/DoubleVecParam.h

    r13395 r13975  
    22 *  \brief: header file for triavertexinput object
    33 */
    4 
    54
    65#ifndef _DOUBLEVECPARAM_H_
     
    2322
    2423        private:
    25                 int enum_type;
    26                 IssmDouble* values;
    27                 int M;
     24                int         enum_type;
     25                IssmDouble *values;
     26                int         M;
    2827
    2928        public:
     
    3736                void  DeepEcho();
    3837                int   Id();
    39                 int   MyRank();
    4038                int   ObjectEnum();
    4139                Object* copy();
     
    5755                void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
    5856                void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
     57                void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
    5958
    6059                void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
     
    7271                void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
    7372                void  UnitConversion(int direction_enum);
    74                
     73
    7574                void GetParameterName(char**pname);
    7675                /*}}}*/
  • issm/trunk/src/c/classes/objects/Params/FileParam.cpp

    r13395 r13975  
    5656int    FileParam::Id(void){ return -1; }
    5757/*}}}*/
    58 /*FUNCTION FileParam::MyRank{{{*/
    59 int    FileParam::MyRank(void){
    60         extern int my_rank;
    61         return my_rank;
    62 }
    63 /*}}}*/
    6458/*FUNCTION FileParam::ObjectEnum{{{*/
    6559int FileParam::ObjectEnum(void){
     
    7165/*FUNCTION FileParam::copy{{{*/
    7266Object* FileParam::copy() {
    73        
     67
    7468        return new FileParam(this->enum_type,this->value);
    7569
  • issm/trunk/src/c/classes/objects/Params/FileParam.h

    r13395 r13975  
    22 *  \brief: header file for triavertexinput object
    33 */
    4 
    54
    65#ifndef _FILEPARAM_H_
     
    3635                void  DeepEcho();
    3736                int   Id();
    38                 int   MyRank();
    3937                int   ObjectEnum();
    4038                Object* copy();
     
    5654                void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
    5755                void  GetParameterValue(FILE** pfid){*pfid=value;};
     56                void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
    5857
    5958                void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a string");}
  • issm/trunk/src/c/classes/objects/Params/GenericParam.h

    r13395 r13975  
    4949                void  Echo() {DeepEcho();};
    5050                int   Id(){ return -1; };
    51                 int   MyRank() { extern int my_rank; return my_rank;} ;
    5251                int   ObjectEnum() {return AdolcParamEnum;};
    5352
     
    8079                void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a Mat");}
    8180                void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a FILE");}
     81                                void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot return a DataSet");}
    8282
    8383                void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(myEnumVal) << " cannot hold a bool");}
     
    9999};
    100100
    101 
    102101#endif /* GENERICPARAM_H_ */
  • issm/trunk/src/c/classes/objects/Params/IntMatParam.cpp

    r13395 r13975  
    5858
    5959        int i,j;
    60        
     60
    6161        _printLine_("IntMatParam:");
    6262        _printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
     
    7272int    IntMatParam::Id(void){ return -1; }
    7373/*}}}*/
    74 /*FUNCTION IntMatParam::MyRank{{{*/
    75 int    IntMatParam::MyRank(void){
    76         extern int my_rank;
    77         return my_rank;
    78 }
    79 /*}}}*/
    8074/*FUNCTION IntMatParam::ObjectEnum{{{*/
    8175int IntMatParam::ObjectEnum(void){
     
    8781/*FUNCTION IntMatParam::copy{{{*/
    8882Object* IntMatParam::copy() {
    89        
     83
    9084        return new IntMatParam(this->enum_type,this->value,this->M,this->N);
    9185
  • issm/trunk/src/c/classes/objects/Params/IntMatParam.h

    r13395 r13975  
    22 *  \brief: header file for triavertexinput object
    33 */
    4 
    54
    65#ifndef _INTMATPARAM_H_
     
    3837                void  DeepEcho();
    3938                int   Id();
    40                 int   MyRank();
    4139                int   ObjectEnum();
    4240                Object* copy();
     
    5856                void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
    5957                void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
     58                void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
    6059
    6160                void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
  • issm/trunk/src/c/classes/objects/Params/IntParam.cpp

    r13395 r13975  
    5656int    IntParam::Id(void){ return -1; }
    5757/*}}}*/
    58 /*FUNCTION IntParam::MyRank{{{*/
    59 int    IntParam::MyRank(void){
    60         extern int my_rank;
    61         return my_rank;
    62 }
    63 /*}}}*/
    6458/*FUNCTION IntParam::ObjectEnum{{{*/
    6559int IntParam::ObjectEnum(void){
     
    7165/*FUNCTION IntParam::copy{{{*/
    7266Object* IntParam::copy() {
    73        
     67
    7468        return new IntParam(this->enum_type,this->value);
    7569
  • issm/trunk/src/c/classes/objects/Params/IntParam.h

    r13395 r13975  
    22 *  \brief: header file for triavertexinput object
    33 */
    4 
    54
    65#ifndef _INTPARAM_H_
     
    3736                void  DeepEcho();
    3837                int   Id();
    39                 int   MyRank();
    4038                int   ObjectEnum();
    4139                Object* copy();
     
    5755                void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
    5856                void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
     57                void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
    5958
    6059                void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a bool");}
  • issm/trunk/src/c/classes/objects/Params/IntVecParam.cpp

    r13395 r13975  
    7373
    7474        int i;
    75        
     75
    7676        _printLine_("IntVecParam:");
    7777        _printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
     
    8585int    IntVecParam::Id(void){ return -1; }
    8686/*}}}*/
    87 /*FUNCTION IntVecParam::MyRank{{{*/
    88 int    IntVecParam::MyRank(void){
    89         extern int my_rank;
    90         return my_rank;
    91 }
    92 /*}}}*/
    9387/*FUNCTION IntVecParam::ObjectEnum{{{*/
    9488int IntVecParam::ObjectEnum(void){
     
    10094/*FUNCTION IntVecParam::copy{{{*/
    10195Object* IntVecParam::copy() {
    102        
     96
    10397        return new IntVecParam(this->enum_type,this->values,this->M);
    10498
  • issm/trunk/src/c/classes/objects/Params/IntVecParam.h

    r13395 r13975  
    22 *  \brief: header file for triavertexinput object
    33 */
    4 
    54
    65#ifndef _INTVECPARAM_H_
     
    3837                void  DeepEcho();
    3938                int   Id();
    40                 int   MyRank();
    4139                int   ObjectEnum();
    4240                Object* copy();
     
    5856                void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
    5957                void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
     58                void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
    6059
    6160                void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
     
    7372                void  SetValue(IssmDouble** array, int M, int* mdim_array, int* ndim_array){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold an array of matrices");}
    7473                void  UnitConversion(int direction_enum);
    75                
     74
    7675                void GetParameterName(char**pname);
    7776                /*}}}*/
  • issm/trunk/src/c/classes/objects/Params/MatrixParam.cpp

    r13395 r13975  
    5555void MatrixParam::DeepEcho(void){
    5656
    57         int i;
    5857        _printLine_("MatrixParam:");
    5958        _printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
     
    6362/*FUNCTION MatrixParam::Id{{{*/
    6463int    MatrixParam::Id(void){ return -1; }
    65 /*}}}*/
    66 /*FUNCTION MatrixParam::MyRank{{{*/
    67 int    MatrixParam::MyRank(void){
    68         extern int my_rank;
    69         return my_rank;
    70 }
    7164/*}}}*/
    7265/*FUNCTION MatrixParam::ObjectEnum{{{*/
     
    7972/*FUNCTION MatrixParam::copy{{{*/
    8073Object* MatrixParam::copy() {
    81        
     74
    8275        return new MatrixParam(this->enum_type,this->value);
    8376
     
    10396/*FUNCTION MatrixParam::SetValue{{{*/
    10497void  MatrixParam::SetValue(Matrix<IssmDouble>* matrix){
    105        
     98
    10699        /*avoid leak: */
    107100        xdelete(&value);
    108        
     101
    109102        /*copy: */
    110103        value=matrix->Duplicate();
  • issm/trunk/src/c/classes/objects/Params/MatrixParam.h

    r13395 r13975  
    22 *  \brief: header file for MatrixParam object
    33 */
    4 
    54
    65#ifndef _MATRIXPARAM_H_
     
    3736                void  DeepEcho();
    3837                int   Id();
    39                 int   MyRank();
    4038                int   ObjectEnum();
    4139                Object* copy();
     
    5755                void  GetParameterValue(Matrix<IssmDouble>** poutput);
    5856                void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
     57                void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
    5958
    6059                void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
  • issm/trunk/src/c/classes/objects/Params/Param.h

    r13395 r13975  
    22 * \brief abstract class for Param object
    33 */
    4 
    54
    65#ifndef _PARAM_H_
     
    4140                virtual void  GetParameterValue(Matrix<IssmDouble>** pmat)=0;
    4241                virtual void  GetParameterValue(FILE** pfid)=0;
    43                
     42                virtual void  GetParameterValue(DataSet** pdataset)=0;
     43
    4444                virtual void  SetValue(bool boolean)=0;
    4545                virtual void  SetValue(int integer)=0;
  • issm/trunk/src/c/classes/objects/Params/StringArrayParam.cpp

    r13395 r13975  
    4646        }
    4747        else value=NULL;
    48        
     48
    4949}
    5050/*}}}*/
    5151/*FUNCTION StringArrayParam::~StringArrayParam(){{{*/
    5252StringArrayParam::~StringArrayParam(){
    53                
     53
    5454        int i;
    55        
     55
    5656        char* string=NULL;
    5757        for(i=0;i<this->numstrings;i++){
     
    8686int    StringArrayParam::Id(void){ return -1; }
    8787/*}}}*/
    88 /*FUNCTION StringArrayParam::MyRank{{{*/
    89 int    StringArrayParam::MyRank(void){
    90         extern int my_rank;
    91         return my_rank;
    92 }
    93 /*}}}*/
    9488/*FUNCTION StringArrayParam::ObjectEnum{{{*/
    9589int StringArrayParam::ObjectEnum(void){
     
    10195/*FUNCTION StringArrayParam::copy{{{*/
    10296Object* StringArrayParam::copy() {
    103        
     97
    10498        return new StringArrayParam(this->enum_type,this->value,this->numstrings);
    10599
     
    110104/*FUNCTION StringArrayParam::GetParameterValue{{{*/
    111105void  StringArrayParam::GetParameterValue(char*** pstringarray,int* pM){
    112        
     106
    113107        int   i;
    114108        char** outstrings=NULL;
     
    146140/*FUNCTION StringArrayParam::SetValue{{{*/
    147141void  StringArrayParam::SetValue(char** stringarray,int M){
    148        
     142
    149143        int   i;
    150144        char *string     = NULL;
  • issm/trunk/src/c/classes/objects/Params/StringArrayParam.h

    r13395 r13975  
    22 *  \brief: header file for triavertexinput object
    33 */
    4 
    54
    65#ifndef _STRINGARRAYPARAM_H_
     
    2827                int      numstrings;
    2928
    30 
    3129        public:
    3230                /*StringArrayParam constructors, destructors: {{{*/
     
    3937                void  DeepEcho();
    4038                int   Id();
    41                 int   MyRank();
    4239                int   ObjectEnum();
    4340                Object* copy();
     
    5956                void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
    6057                void  GetParameterValue(FILE** pfid){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a FILE");}
     58                void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
    6159
    6260                void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
  • issm/trunk/src/c/classes/objects/Params/StringParam.cpp

    r13395 r13975  
    3333        xMemCpy<char>(value,in_value,(strlen(in_value)+1));
    3434
    35        
    3635}
    3736/*}}}*/
     
    5857int    StringParam::Id(void){ return -1; }
    5958/*}}}*/
    60 /*FUNCTION StringParam::MyRank{{{*/
    61 int    StringParam::MyRank(void){
    62         extern int my_rank;
    63         return my_rank;
    64 }
    65 /*}}}*/
    6659/*FUNCTION StringParam::ObjectEnum{{{*/
    6760int StringParam::ObjectEnum(void){
     
    7366/*FUNCTION StringParam::copy{{{*/
    7467Object* StringParam::copy() {
    75        
     68
    7669        return new StringParam(this->enum_type,this->value);
    7770
     
    8275/*FUNCTION StringParam::GetParameterValue{{{*/
    8376void  StringParam::GetParameterValue(char** pstring){
    84        
     77
    8578        char* outstring=NULL;
    8679        int   stringsize;
     
    10295/*FUNCTION StringParam::SetValue{{{*/
    10396void  StringParam::SetValue(char* string){
    104        
     97
    10598        int   stringsize;
    106        
     99
    107100        /*avoid leak: */
    108101        xDelete<char>(this->value);
  • issm/trunk/src/c/classes/objects/Params/StringParam.h

    r13395 r13975  
    22 *  \brief: header file for triavertexinput object
    33 */
    4 
    54
    65#ifndef _STRINGPARAM_H_
     
    2423        private:
    2524                /*just hold 3 values for 3 vertices: */
    26                 int enum_type;
    27                 char* value;
     25                int   enum_type;
     26                char *value;
    2827
    2928        public:
     
    3736                void  DeepEcho();
    3837                int   Id();
    39                 int   MyRank();
    4038                int   ObjectEnum();
    4139                Object* copy();
     
    5755                void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a Mat");}
    5856                void  GetParameterValue(FILE** pfid){_error_("Bool param of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a FILE");}
     57                void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
    5958
    6059                void  SetValue(bool boolean){_error_("Param "<< EnumToStringx(enum_type) << " cannot hold a boolean");}
  • issm/trunk/src/c/classes/objects/Params/TransientParam.cpp

    r13395 r13975  
    6161void TransientParam::DeepEcho(void){
    6262
    63         int i,j;
    64        
    6563        _printLine_("TransientParam:");
    6664        _printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
    6765        _printLine_("   size: " << this->N);
    68         for(i=0;i<this->N;i++){
     66        for(int i=0;i<this->N;i++){
    6967                _printLine_(   "time: " << this->timesteps[i] << " value: " << this->values[i]);
    7068        }
     
    7371/*FUNCTION TransientParam::Id{{{*/
    7472int    TransientParam::Id(void){ return -1; }
    75 /*}}}*/
    76 /*FUNCTION TransientParam::MyRank{{{*/
    77 int    TransientParam::MyRank(void){
    78         extern int my_rank;
    79         return my_rank;
    80 }
    8173/*}}}*/
    8274/*FUNCTION TransientParam::ObjectEnum{{{*/
     
    8981/*FUNCTION TransientParam::copy{{{*/
    9082Object* TransientParam::copy() {
    91        
     83
    9284        return new TransientParam(this->enum_type,this->values,this->timesteps,this->N);
    9385
  • issm/trunk/src/c/classes/objects/Params/TransientParam.h

    r13395 r13975  
    22 *  \brief: header file for triavertexinput object
    33 */
    4 
    54
    65#ifndef _TRANSIENTPARAM_H_
     
    2322
    2423        protected:
    25                 int enum_type;
    26                 int N;
    27                 IssmDouble* values;
    28                 IssmDouble* timesteps;
     24                int         enum_type;
     25                int         N;
     26                IssmDouble *values;
     27                IssmDouble *timesteps;
    2928
    3029        public:
     
    3837                void  DeepEcho();
    3938                int   Id();
    40                 int   MyRank();
    4139                int   ObjectEnum();
    4240                Object* copy();
     
    5856                void  GetParameterValue(Matrix<IssmDouble>** pmat){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a Mat");}
    5957                void  GetParameterValue(FILE** pfid){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot return a FILE");}
     58                void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
    6059
    6160                void  SetValue(bool boolean){_error_("Parameter " <<EnumToStringx(enum_type) << " cannot hold a boolean");}
  • issm/trunk/src/c/classes/objects/Params/VectorParam.cpp

    r13395 r13975  
    5757void VectorParam::DeepEcho(void){
    5858
    59         int i;
    6059        _printLine_("VectorParam:");
    6160        _printLine_("   enum: " << this->enum_type << " (" << EnumToStringx(this->enum_type) << ")");
     
    6564/*FUNCTION VectorParam::Id{{{*/
    6665int    VectorParam::Id(void){ return -1; }
    67 /*}}}*/
    68 /*FUNCTION VectorParam::MyRank{{{*/
    69 int    VectorParam::MyRank(void){
    70         extern int my_rank;
    71         return my_rank;
    72 }
    7366/*}}}*/
    7467/*FUNCTION VectorParam::ObjectEnum{{{*/
     
    8174/*FUNCTION VectorParam::copy{{{*/
    8275Object* VectorParam::copy() {
    83        
     76
    8477        return new VectorParam(this->enum_type,this->value);
    8578
     
    109102        /*avoid leak: */
    110103        xdelete(&value);
    111        
     104
    112105        /*copy: */
    113106        value=vector->Duplicate();
  • issm/trunk/src/c/classes/objects/Params/VectorParam.h

    r13395 r13975  
    22 *  \brief: header file for triavertexinput object
    33 */
    4 
    54
    65#ifndef _VECTORPARAM_H_
     
    3736                void  DeepEcho();
    3837                int   Id();
    39                 int   MyRank();
    4038                int   ObjectEnum();
    4139                Object* copy();
     
    5755                void  GetParameterValue(Vector<IssmDouble>** poutput);
    5856                void  GetParameterValue(FILE** pfid){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot return a FILE");}
     57                void  GetParameterValue(DataSet** pdataset){_error_("Param "<< EnumToStringx(enum_type) << " cannot return a DataSet");}
    5958
    6059                void  SetValue(bool boolean){_error_("Vector of enum " << enum_type << " (" << EnumToStringx(enum_type) << ") cannot hold a boolean");}
  • issm/trunk/src/c/classes/objects/Segment.h

    r13395 r13975  
    1515
    1616        public:
    17                 int eid;
     17                int        eid;
    1818                doubletype x1;
    1919                doubletype y1;
     
    2121                doubletype y2;
    2222
    23 
    2423                /*Segment constructors, destructors :*/
    2524                /*FUNCTION Segment() default constructor {{{*/
    2625                Segment(){
    27                         this->eid=UNDEF;
    28                         this->x1=UNDEF;
    29                         this->y1=UNDEF;
    30                         this->x2=UNDEF;
    31                         this->y2=UNDEF;
     26                        this->eid = UNDEF;
     27                        this->x1  = UNDEF;
     28                        this->y1  = UNDEF;
     29                        this->x2  = UNDEF;
     30                        this->y2  = UNDEF;
    3231                }
    3332                /*}}}*/
     
    3534                Segment(int segment_eid, doubletype segment_x1,doubletype segment_y1,doubletype segment_x2, doubletype segment_y2){
    3635
    37                         this->eid=segment_eid;
    38                         this->x1=segment_x1;
    39                         this->y1=segment_y1;
    40                         this->x2=segment_x2;
    41                         this->y2=segment_y2;
     36                        this->eid = segment_eid;
     37                        this->x1  = segment_x1;
     38                        this->y1  = segment_y1;
     39                        this->x2  = segment_x2;
     40                        this->y2  = segment_y2;
    4241
    4342                }
     
    6766                int    Id(void){ return eid; }
    6867                /*}}}*/
    69                 /*FUNCTION MyRank{{{*/
    70                 int    MyRank(void){
    71                         extern int my_rank;
    72 
    73                         return my_rank;
    74                 }
    75                 /*}}}*/
    7668                /*FUNCTION ObjectEnum{{{*/
    7769                int ObjectEnum(void){
     
    8476                Object* copy() {
    8577                        return new Segment(this->eid,this->x1,this->y1,this->x2,this->y2);
    86 
    8778                }
    88 
    8979                /*}}}*/
    9080
  • issm/trunk/src/c/classes/objects/Vertex.cpp

    r13395 r13975  
    4949        this->id=vertex_id;
    5050        this->sid=vertex_sid;
     51        this->pid=UNDEF;
    5152        this->x=vertex_x;
    5253        this->y=vertex_y;
     
    5455        this->sigma=vertex_sigma;
    5556        this->connectivity=vertex_connectivity;
    56         this->dof=UNDEF;
    5757
    5858        return;
     
    6767        _printLine_("   id: " << id);
    6868        _printLine_("   sid: " << sid);
     69        _printLine_("   pid: " << pid);
    6970        _printLine_("   x: " << x);
    7071        _printLine_("   y: " << y);
     
    7273        _printLine_("   sigma: " << sigma);
    7374        _printLine_("   connectivity: " << connectivity);
    74         _printLine_("   dof: " << dof);
    7575        _printLine_("   clone: " << clone);
    7676
     
    8686int    Vertex::Id(void){ return id; }
    8787/*}}}*/
    88 /*FUNCTION Vertex::MyRank {{{*/
    89 int    Vertex::MyRank(void){
    90         extern int my_rank;
    91         return my_rank;
    92 }
    93 /*}}}*/
    9488/*FUNCTION Vertex::ObjectEnum{{{*/
    9589int Vertex::ObjectEnum(void){
     
    10397
    10498        return new Vertex(*this);
    105 
    106 }
    107 /*}}}*/
    108 
    109 /* DofObject routines: */
    110 /*FUNCTION Vertex::DistributeDofs{{{*/
    111 void  Vertex::DistributeDofs(int* pdofcount){
    112 
    113         int i;
    114         extern int my_rank;
    115         int dofcount;
    116 
    117         dofcount=*pdofcount;
    118        
    119         if(this->clone){
    120                 /*This vertex is a clone! Don't distribute dofs, it will get them from another cpu!*/
    121                 return;
    122         }
    123 
    124         /*This vertex should distribute his dof, go ahead: */
    125         this->dof=dofcount;
    126         dofcount++;
    127 
    128         /*Assign output pointers: */
    129         *pdofcount=dofcount;
    130 
    131 }
    132 /*}}}*/
    133 /*FUNCTION Vertex::OffsetDofs{{{*/
    134 void  Vertex::OffsetDofs(int dofcount){
    135        
    136         int i;
    137         extern int my_rank;
    138        
    139         if(this->clone){
    140                 /*This vertex is a clone, don't offset the dofs!: */
    141                 return;
    142         }
    143 
    144         /*This vertex should offset his dof, go ahead: */
    145         this->dof+=dofcount;
    146 }
    147 /*}}}*/
    148 /*FUNCTION Vertex::ShowTrueDofs{{{*/
    149 void  Vertex::ShowTrueDofs(int* truedofs){
    150 
    151         int j;
    152         extern int my_rank;
    153        
    154         /*Are we a clone? : */
    155         if(this->clone)return;
    156 
    157         /*Ok, we are not a clone, just plug our dof into truedofs: */
    158         truedofs[this->id-1]=this->dof;
    159 
    160 }
    161 /*}}}*/
    162 /*FUNCTION Vertex::UpdateCloneDofs{{{*/
    163 void  Vertex::UpdateCloneDofs(int* alltruedofs){
    164 
    165         int j;
    166         extern int my_rank;
    167        
    168         /*If we are not a clone, don't update, we already have dofs!: */
    169         if(this->clone==0)return;
    170 
    171         /*Ok, we are a clone node, but we did not create the dof for this vertex
    172          * Therefore, our dof is garbage right now. Go pick it up in the alltruedofs: */
    173         this->dof=alltruedofs[id-1];
    174 }
    175 /*}}}*/
    176 /*FUNCTION Vertex::SetClone {{{*/
    177 void  Vertex::SetClone(int* minranks){
    178 
    179         extern int my_rank;
    180 
    181         if (minranks[id-1]==my_rank){
    182                 this->clone=0;
    183         }
    184         else{
    185                 /*!there is a cpu with lower rank that has the same vertex,
    186                 therefore, I am a clone*/
    187                 this->clone=1; 
    188         }
    18999
    190100}
     
    209119        /*sigma remains constant. z=bed+sigma*thickness*/
    210120        oldz = this->z;
    211         newz = bed[this->dof]+sigma*thickness[this->dof];
     121        newz = bed[this->pid]+sigma*thickness[this->pid];
    212122        velz = (newz-oldz)/dt;
    213123        this->z = newz;
    214124
    215125        /*put vz in vector*/
    216         vz->SetValue(this->dof,velz,INS_VAL);
     126        vz->SetValue(this->pid,velz,INS_VAL);
    217127}
    218128/*}}}*/
     129/*FUNCTION Vertex::DistributePids{{{*/
     130void  Vertex::DistributePids(int* ppidcount){
     131
     132        /*retrieve current pid*/
     133        int pidcount=*ppidcount;
     134
     135        /*This vertex is a clone! Don't distribute pids, it will get them from another cpu!*/
     136        if(this->clone) return;
     137
     138        /*This vertex should distribute its pid*/
     139        this->pid=pidcount;
     140        pidcount++;
     141
     142        /*Assign output pointers: */
     143        *ppidcount=pidcount;
     144}
     145/*}}}*/
     146/*FUNCTION Vertex::OffsetPids{{{*/
     147void  Vertex::OffsetPids(int pidcount){
     148
     149        /*This vertex is a clone, don't offset the pids*/
     150        if(this->clone) return;
     151
     152        /*This vertex should offset his pid, go ahead: */
     153        this->pid+=pidcount;
     154}
     155/*}}}*/
     156/*FUNCTION Vertex::ShowTruePids{{{*/
     157void  Vertex::ShowTruePids(int* truepids){
     158
     159        /*Are we a clone? : */
     160        if(this->clone)return;
     161
     162        /*Ok, we are not a clone, just plug our pid into truepids: */
     163        truepids[this->sid]=this->pid;
     164}
     165/*}}}*/
     166/*FUNCTION Vertex::UpdateClonePids{{{*/
     167void  Vertex::UpdateClonePids(int* alltruepids){
     168
     169        /*If we are not a clone, don't update, we already have pids: */
     170        if(!this->clone)return;
     171
     172        /*Ok, we are a clone node, but we did not create the pid for this vertex
     173         * Therefore, our pid is garbage right now. Go pick it up in the alltruepids: */
     174        this->pid=alltruepids[this->sid];
     175}
     176/*}}}*/
     177/*FUNCTION Vertex::SetClone {{{*/
     178void  Vertex::SetClone(int* minranks){
     179
     180        int my_rank;
     181
     182        /*recover my_rank:*/
     183        my_rank=IssmComm::GetRank();
     184
     185        if (minranks[this->sid]==my_rank){
     186                this->clone=false;
     187        }
     188        else{
     189                /*!there is a cpu with lower rank that has the same vertex,
     190                therefore, I am a clone*/
     191                this->clone=true;
     192        }
     193
     194}
     195/*}}}*/
  • issm/trunk/src/c/classes/objects/Vertex.h

    r13395 r13975  
    99/*{{{*/
    1010#include "../classes.h"
    11 class IoModel;
    12 template <class doubletype> class Vector;
    13 class Parameters;
    1411#include "../../shared/Exceptions/exceptions.h"
    1512#include "../../toolkits/toolkits.h"
    1613#include "../../include/include.h"
    17 
     14template <class doubletype> class Vector;
     15class Parameters;
     16class IoModel;
    1817/*}}}*/
    19 
    2018
    2119class Vertex: public Object{
    2220
    2321        public:
    24 
    25                 int    id;
    26                 int    sid;            //sid for "serial" id, ie the rank of this vertex in the vertices dataset, if the dataset was serial on 1 cpu.
     22                bool       clone;
     23                int        id;           // random index
     24                int        sid;          // "serial" id (rank of this vertex if the dataset was on 1 cpu)
     25                int        pid;          // "parallel" id
    2726                IssmDouble x;
    2827                IssmDouble y;
    2928                IssmDouble z;
    30                 IssmDouble sigma;          //sigma coordinate: (z-bed)/thickness
    31                 int    connectivity;   //number of vertices connected to this vertex
    32 
    33                 /*dof management: */
    34                 int    clone;
    35                 int    dof; //dof to recover values in a vertex indexed vector
     29                IssmDouble sigma;        //sigma coordinate: (z-bed)/thickness
     30                int        connectivity; //number of vertices connected to this vertex
    3631
    3732                /*Vertex constructors, destructors {{{*/
     
    4641                void  DeepEcho();
    4742                int   Id();
    48                 int   MyRank();
    4943                int   ObjectEnum();
    5044                Object* copy();
    5145                /*}}}*/
    52                 /*DofObject routines {{{*/
    53                 void  DistributeDofs(int* pdofcount);
    54                 void  OffsetDofs(int dofcount);
    55                 void  ShowTrueDofs(int* borderdofs);
    56                 void  UpdateCloneDofs(int* allborderdofs);
    57                 void  SetClone(int* minranks);
    58                 /*}}}*/
    59                 /*Vertex management: {{{*/
     46                /*Vertex management:*/
    6047                int   Sid(void);
    6148                int   Connectivity(void);
    6249                void  UpdatePosition(Vector<IssmDouble>* vz,Parameters* parameters,IssmDouble* thickness,IssmDouble* bed);
    63                 /*}}}*/
     50                void  DistributePids(int* ppidcount);
     51                void  OffsetPids(int pidcount);
     52                void  ShowTruePids(int* borderpids);
     53                void  UpdateClonePids(int* allborderpids);
     54                void  SetClone(int* minranks);
    6455};
    6556#endif  /* _VERTEX_H */
  • issm/trunk/src/c/classes/objects/objects.h

    r13395 r13975  
    1313#include "./Vertex.h"
    1414#include "./Node.h"
     15#include "./Profiler.h"
     16#include "./DependentObject.h"
     17#include "./IndependentObject.h"
    1518#include "./Segment.h"
    1619
     
    119122#include "./Params/StringParam.h"
    120123#include "./Params/TransientParam.h"
     124#include "./Params/DataSetParam.h"
    121125
    122126#endif
  • issm/trunk/src/c/include/globals.h

    r11995 r13975  
    66#define GLOBALS_H_
    77
    8 int my_rank=0;
    9 int num_procs=1;
     8#include "./types.h"
     9#include "../classes/IssmComm.h"
     10
     11COMM IssmComm::comm;
    1012
    1113#endif
  • issm/trunk/src/c/include/macros.h

    r13395 r13975  
    2323#define _printf_(flag,...) do{if(flag) PrintfFunction(__VA_ARGS__);}while(0)
    2424/*}}}*/
    25 /* _error2_ {{{*/
     25/* _error_ {{{*/
    2626/*new Error exception macro*/
    2727#ifdef _INTEL_WIN_
     
    7171#endif
    7272/*}}}*/
    73 /* ISSMBOOT/ISSMEND {{{*/
     73/* ExceptionTrapBegin/ExceptionTrapEnd {{{*/
    7474
    7575/*The following macros hide the error exception handling in a matlab module. Just put
    76  * ISSMBOOT(); and ISSMEND(); at the beginning and end of a module, and c++ exceptions
     76 * ExceptionTrapBegin(); and ExceptionTrapEnd(); at the beginning and end of a module, and c++ exceptions
    7777 * will be trapped. Really nifty!*/
    7878
    79 #define ISSMBOOT(); \
     79#define ExceptionTrapBegin(); \
    8080        try{
    8181
    82 #define ISSMEND(); }\
     82#define ExceptionTrapEnd(); }\
    8383        catch(ErrorException &exception){\
    84                 exception.Report(); \
    85                 return 1;\
     84                exception.Report();\
     85                return 0;\
    8686        }\
    8787        catch (exception& e) {\
    8888                _printf_(true,"Standard exception: %s\n",e.what());\
    89                 return 1;\
     89                return 0;\
    9090        }\
    9191        catch(...){\
    9292                _printf_(true,"An unexpected error occurred");\
     93                return 0;\
    9394        }
    9495/*}}}*/
  • issm/trunk/src/c/include/typedefs.h

    r12706 r13975  
    3636#define INFINITY (DBL_MAX+DBL_MAX)
    3737#define NAN (INFINITY-INFINITY)
    38        
     38
    3939#endif
    4040
  • issm/trunk/src/c/include/types.h

    r12706 r13975  
    55#ifndef _TYPES_H_
    66#define  _TYPES_H_
    7 
    87
    98#ifdef HAVE_CONFIG_H
     
    2726#endif 
    2827
    29 #ifdef _HAVE_ADOLC_
     28#if defined(_HAVE_ADOLC_) &&  !defined(_WRAPPERS_)
    3029#include "adolc/adolc.h"
    3130// for active variables
     
    4039#endif
    4140
    42 typedef bool IssmBool;
     41/*Define communicator: */
     42#ifdef _HAVE_MPI_
     43#include <mpi.h>
     44typedef MPI_Comm COMM;
     45#else
     46typedef int COMM;
     47#endif
    4348
    4449#endif //ifndef _TYPES_H_
  • issm/trunk/src/c/io/Disk/diskio.h

    r13395 r13975  
    1010FILE* pfopen(char* filename,const char* format);
    1111void  pfclose(FILE* fid,char* filename);
     12void WriteLockFile(char* filename);
    1213
    1314#endif  /* _IO_H_ */
  • issm/trunk/src/c/io/Disk/pfclose.cpp

    r13395 r13975  
    1616
    1717        /*Close file handle: */
    18         extern int my_rank;
    1918        _assert_(fid);
    2019        if(fclose(fid)!=0)_error_("could not close file " << filename);
  • issm/trunk/src/c/io/Disk/pfopen.cpp

    r13395 r13975  
    1616
    1717        FILE* fid=NULL;
    18         extern int my_rank;
    19        
     18
    2019        /*Open handle to data on disk: */
    2120        fid=fopen(filename,format);
     
    2423        return fid;
    2524}
    26 
  • issm/trunk/src/c/io/PrintfFunction.cpp

    r12706 r13975  
    1515        char *buffer = NULL;
    1616        int   n,size = 100;
    17         int         string_size;
    18         extern int  my_rank;
    19         extern int  num_procs;
    20                                                                                                                                                                                                      
     17        int   my_rank;
    2118        //variable list of arguments
    2219        va_list args;
     20
     21        /*recover my_rank:*/
     22        my_rank=IssmComm::GetRank();
    2323
    2424        while(true){
     
    5252}
    5353int PrintfFunction(const string & message){
    54         extern int  my_rank;
     54        int  my_rank;
     55
     56        /*recover my_rank:*/
     57        my_rank=IssmComm::GetRank();
     58
    5559        if(my_rank==0){
    5660                printf("%s\n",message.c_str());
     
    5963}
    6064int PrintfFunction2(const string & message){
    61         extern int  my_rank;
     65        int  my_rank;
     66
     67        /*recover my_rank:*/
     68        my_rank=IssmComm::GetRank();
     69
    6270        if(my_rank==0){
    6371                printf("%s",message.c_str());
  • issm/trunk/src/c/issm.h

    r13395 r13975  
    1212#endif
    1313
     14#include "./include/globals.h" //only include this header file once!
    1415#include "./include/include.h"
    1516#include "./shared/shared.h"
  • issm/trunk/src/c/modules/AverageFilterx/AverageFilterx.cpp

    r12706 r13975  
    1111
    1212int AverageFilterx(double** pimageout,double* image, int lines,int samps,int smooth){
    13        
     13
    1414        double      temp;
    1515        int         numvalues;
  • issm/trunk/src/c/modules/AverageFilterx/AverageFilterx.h

    r3109 r13975  
    1111/* local prototypes: */
    1212int AverageFilterx(double** pimageout,double* imagein, int lines,int samp,int smooth);
    13        
     13
    1414#endif /* AVERAGEFILTERX_H */
    15 
  • issm/trunk/src/c/modules/AverageOntoPartitionx/AverageOntoPartitionx.cpp

    r13395 r13975  
    1818#include "../modules.h"
    1919
    20                        
    2120void AverageOntoPartitionx(double** paverage, Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* vertex_response){
    2221
    23         int     i,j,k;
    2422        int     dummy;
    25 
    2623        int     npart;
    2724        double *qmu_part  = NULL;
     
    4946
    5047        /*loop on each element, and add contribution of the element to the partition (surface weighted average): */
    51         for(i=0;i<elements->Size();i++){
    52                 Element* element=(Element*)elements->GetObjectByOffset(i);
     48        for(int i=0;i<elements->Size();i++){
     49                Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    5350                element->AverageOntoPartition(partition_contributions,partition_areas,vertex_response,qmu_part);
    5451        }
  • issm/trunk/src/c/modules/Bamgx/Bamgx.cpp

    r13395 r13975  
    2020
    2121        /*intermediary*/
     22        int i;
    2223        int noerr=1;
    23         int i,j,num;
    2424        double costheta=2;
    2525        double hminaniso=1e-100;
  • issm/trunk/src/c/modules/Chacox/Chacox.cpp

    r12706 r13975  
    2121{
    2222        #ifdef _HAVE_CHACO_ //only works if Chaco library has been compiled in.
    23        
    24        
     23
    2524        extern int Using_Main;  /* is main routine being called? */
    2625        extern char *PARAMS_FILENAME;   /* name of file with parameter updates */
     
    6261        int i,tvwgt;
    6362        double tgoal;
    64 
    65 
    6663
    6764        if (DEBUG_TRACE > 0) {
     
    187184                _printLine_("<Leaving main>");
    188185        }
    189        
     186
    190187        return(0);
    191 
    192188
    193189        #else //ifdef _HAVE_CHACO_
  • issm/trunk/src/c/modules/Chacox/Chacox.h

    r13395 r13975  
    4444#define __FUNCT__  "Chacox"
    4545
    46 
    4746#endif  /* _CHACOX_H */
  • issm/trunk/src/c/modules/Chacox/chaco_seconds.cpp

    r11237 r13975  
    88#endif
    99
     10double chaco_seconds(void){
    1011
    11 
    12 double chaco_seconds(void){
    13    
    1412        double    curtime;
    1513
     
    2220         *is defined in the <sys/time.h> and <sys/resource.h> header files. Leaving it
    2321         *for reference in case we have a problem here in the future*/
    24  
     22
    2523    getrusage(RUSAGE_SELF, &rusage);
    2624    curtime = ((rusage.ru_utime.tv_sec + rusage.ru_stime.tv_sec) +
  • issm/trunk/src/c/modules/Chacox/input_parse.cpp

    r12706 r13975  
    44
    55#include "./Chacox.h"
    6 
    76
    87#undef __FUNCT__
  • issm/trunk/src/c/modules/Chacox/user_params.cpp

    r9320 r13975  
    1414#endif
    1515
    16 
    1716#ifdef _HAVE_CHACO_ //only works if dakota library has been compiled in.
    1817
     
    2120#define  TRUE  1
    2221#define  FALSE 0
    23 
    2422
    2523/* Input and ouput control parameters */
     
    3432int       PROMPT = FALSE;        /* Prompt for input? (TRUE/FALSE) */
    3533int       PRINT_HEADERS = FALSE; /* Print pretty output headers (TRUE/FALSE) */
    36 
    3734
    3835/* Eigenvector calculation parameters */
     
    5754int       TIME_KERNELS = FALSE; /* Time numerical kernels? (TRUE/FALSE) */
    5855
    59 
    6056/* Other parameters for spectral methods */
    6157
     
    6965int       OPT3D_NTRIES = 5;     /* # local opts to look for global min in opt3d */
    7066
    71 
    7267/* Kernighan--Lin/Fiduccia--Mattheyses parameters */
    7368
     
    7873int       KL_UNDO_LIST = TRUE;  /* Only resort changed vtxs? (TRUE/FALSE) */
    7974double    KL_IMBALANCE = 0.0;   /* Fractional imbalance allowed by KL */
    80 
    8175
    8276/* Coarsening parameters */
     
    9185int       KL_ONLY_BNDY = TRUE;     /* Start moving vtxs on boundary? (TRUE/FALSE) */
    9286
    93 
    9487/* Parameters for post-processing options */
    9588
     
    9790int       INTERNAL_VERTICES = FALSE;    /* ... to up internal vtxs? (TRUE/FALSE) */
    9891int       REFINE_MAP = FALSE;           /* ... to reduce hops? (TRUE/FALSE) */
    99 
    10092
    10193/* Architecture and simulator parameters */
     
    129121char     *PARAMS_FILENAME = "User_Params";      /* File of parameter changes */
    130122
    131 
    132123/* Parameters that control debugging output */
    133124
     
    151142int       DEBUG_MACH_PARAMS = 0;/* Print computed machine params? (0..1) */
    152143
    153 
    154144#endif //ifdef _HAVE_CHACO_
  • issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.cpp

    r13395 r13975  
    2929        /*Compute basal stress for each element: */
    3030        for (i=0;i<elements->Size();i++){
    31                 element=(Element*)elements->GetObjectByOffset(i);
     31                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    3232                element->ComputeBasalStress(sigma);
    3333        }
     
    3838        /*Assign output pointers: */
    3939        *psigma=sigma;
    40        
     40
    4141}
  • issm/trunk/src/c/modules/ComputeBasalStressx/ComputeBasalStressx.h

    r13395 r13975  
    1313
    1414#endif  /* _COMPUTEBASALSTRESSX_H */
    15 
  • issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.cpp

    r13395 r13975  
    2929        /*Compute basal stress for each element: */
    3030        for (i=0;i<elements->Size();i++){
    31                 element=(Element*)elements->GetObjectByOffset(i);
     31                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    3232                element->ComputeStrainRate(eps);
    3333        }
     
    3838        /*Assign output pointers: */
    3939        *peps=eps;
    40        
     40
    4141}
  • issm/trunk/src/c/modules/ComputeStrainRatex/ComputeStrainRatex.h

    r13395 r13975  
    1313
    1414#endif  /* _COMPUTESTRAINRATEX_H */
    15 
  • issm/trunk/src/c/modules/ConfigureObjectsx/ConfigureObjectsx.cpp

    r12706 r13975  
    2424        /*Get analysis type: */
    2525        parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
    26        
     26
    2727        if(VerboseMProcessor()) _pprintLine_("      Configuring elements...");
    2828        for (i=0;i<elements->Size();i++){
    29                 element=(Element*)elements->GetObjectByOffset(i);
     29                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    3030                element->Configure(elements,loads,nodes,materials,parameters);
    3131        }
     
    4444                }
    4545        }
    46        
     46
    4747        if(VerboseMProcessor()) _pprintLine_("      Configuring materials...");
    4848        for (i=0;i<materials->Size();i++){
  • issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStateLocal.h

    r13395 r13975  
    2727
    2828#endif  /* _CONSTRAINTSSTATEX_H */
    29 
  • issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.cpp

    r12706 r13975  
    1313void ConstraintsStatex(int* pconverged, int* pnum_unstable_constraints, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,  Parameters* parameters){
    1414
    15         int i;
    16 
    17         extern int num_procs;
    18         extern int my_rank;
    19        
    2015        /*output: */
    2116        int converged=0;
     
    4641                converged=1;
    4742        }
    48                
     43
    4944        /*Assign output pointers: */
    5045        *pconverged=converged;
  • issm/trunk/src/c/modules/ConstraintsStatex/ConstraintsStatex.h

    r13395 r13975  
    1515
    1616#endif  /* _CONSTRAINTSSTATEX_H */
    17 
  • issm/trunk/src/c/modules/ConstraintsStatex/RiftConstraintsState.cpp

    r12706 r13975  
    1515int RiftIsPresent(Loads* loads,int configuration_type){
    1616
    17 
    1817        int i;
    19        
     18
    2019        int found=0;
    2120        int mpi_found=0;
     
    3332
    3433        #ifdef _HAVE_MPI_
    35         MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
    36         MPI_Bcast(&mpi_found,1,MPI_INT,0,MPI_COMM_WORLD);               
     34        MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
     35        MPI_Bcast(&mpi_found,1,MPI_INT,0,IssmComm::GetComm());               
    3736        found=mpi_found;
    3837        #endif
     
    4645        int num_unstable_constraints=0;
    4746        int converged=0;
    48         int potential;
    4947
    5048        RiftConstrain(&num_unstable_constraints,loads,configuration_type);
    5149        if(num_unstable_constraints==0)converged=1;
    52        
     50
    5351        if(RiftIsFrozen(loads,configuration_type)){
    5452                converged=1;
     
    6967
    7068        int                     i;
    71        
     69
    7270        /* generic object pointer: */
    7371        Riftfront* riftfront=NULL;
     
    7775        int sum_num_unstable_constraints;
    7876        int num_unstable_constraints=0;
    79                
     77
    8078        /*Enforce constraints: */
    8179        for (i=0;i<loads->Size();i++){
     
    9694
    9795        #ifdef _HAVE_MPI_
    98         MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
    99         MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,MPI_COMM_WORLD);               
     96        MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
     97        MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,IssmComm::GetComm());               
    10098        num_unstable_constraints=sum_num_unstable_constraints;
    10199        #endif
    102        
     100
    103101        /*Assign output pointers: */
    104102        *pnum_unstable_constraints=num_unstable_constraints;
     
    110108
    111109        int                     i;
    112        
     110
    113111        /* generic object pointer: */
    114112        Load*      load=NULL;
     
    121119
    122120                if (RiftfrontEnum==loads->GetEnum(i)){
    123                        
     121
    124122                        load=(Load*)loads->GetObjectByOffset(i);
    125123                        if(load->InAnalysis(configuration_type)){
     
    133131                }
    134132        }
    135        
     133
    136134        /*Is there just one found? that would mean we have frozen! : */
    137135        #ifdef _HAVE_MPI_
    138         MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD );
    139         MPI_Bcast(&mpi_found,1,MPI_INT,0,MPI_COMM_WORLD);               
     136        MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_MAX,0,IssmComm::GetComm() );
     137        MPI_Bcast(&mpi_found,1,MPI_INT,0,IssmComm::GetComm());               
    140138        found=mpi_found;
    141139        #endif
     
    148146
    149147        int                     i;
    150        
     148
    151149        /* generic object pointer: */
    152150        Load*      load=NULL;
     
    160158                        load=(Load*)loads->GetObjectByOffset(i);
    161159                        if(load->InAnalysis(configuration_type)){
    162                                
     160
    163161                                riftfront=(Riftfront*)load;
    164162                                riftfront->FreezeConstraints();
     
    176174
    177175        int i;
    178        
     176
    179177        Riftfront* riftfront=NULL;
    180178        int found=0;
     
    196194
    197195        #ifdef _HAVE_MPI_
    198         MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
    199         MPI_Bcast(&mpi_found,1,MPI_INT,0,MPI_COMM_WORLD);               
     196        MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
     197        MPI_Bcast(&mpi_found,1,MPI_INT,0,IssmComm::GetComm());               
    200198        found=mpi_found;
    201199        #endif
     
    207205int RiftIsPreStable(Loads* loads){
    208206
    209 
    210207        int i;
    211        
     208
    212209        Riftfront* riftfront=NULL;
    213210        int found=0;
     
    229226
    230227        #ifdef _HAVE_MPI_
    231         MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
    232         MPI_Bcast(&mpi_found,1,MPI_INT,0,MPI_COMM_WORLD);               
     228        MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
     229        MPI_Bcast(&mpi_found,1,MPI_INT,0,IssmComm::GetComm());               
    233230        found=mpi_found;
    234231        #endif
     
    246243void RiftSetPreStable(Loads* loads){
    247244
    248 
    249245        int i;
    250        
     246
    251247        Riftfront* riftfront=NULL;
    252248        int found=0;
     
    268264
    269265        int                     i;
    270        
     266
    271267        /* generic object pointer: */
    272268        Riftfront* riftfront=NULL;
     
    275271        int sum_num_unstable_constraints;
    276272        int num_unstable_constraints=0;
    277                
     273
    278274        /*Enforce constraints: */
    279275        for (i=0;i<loads->Size();i++){
     
    290286
    291287        #ifdef _HAVE_MPI_
    292         MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
    293         MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,MPI_COMM_WORLD);               
     288        MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
     289        MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,IssmComm::GetComm());               
    294290        num_unstable_constraints=sum_num_unstable_constraints;
    295291        #endif
    296        
     292
    297293        /*Assign output pointers: */
    298294        *pnum_unstable_constraints=num_unstable_constraints;
     
    304300
    305301        int                     i;
    306        
     302
    307303        /* generic object pointer: */
    308304        Riftfront* riftfront=NULL;
     
    330326
    331327        #ifdef _HAVE_MPI_
    332         MPI_Reduce (&max_penetration,&mpi_max_penetration,1,MPI_DOUBLE,MPI_MAX,0,MPI_COMM_WORLD );
    333         MPI_Bcast(&mpi_max_penetration,1,MPI_DOUBLE,0,MPI_COMM_WORLD);               
     328        MPI_Reduce (&max_penetration,&mpi_max_penetration,1,MPI_DOUBLE,MPI_MAX,0,IssmComm::GetComm() );
     329        MPI_Bcast(&mpi_max_penetration,1,MPI_DOUBLE,0,IssmComm::GetComm());               
    334330        max_penetration=mpi_max_penetration;
    335331        #endif
     
    346342
    347343        int                     i;
    348        
     344
    349345        /* generic object pointer: */
    350346        Riftfront* riftfront=NULL;
     
    369365
    370366        #ifdef _HAVE_MPI_
    371         MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
    372         MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,MPI_COMM_WORLD);               
     367        MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
     368        MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,IssmComm::GetComm());               
    373369        num_unstable_constraints=sum_num_unstable_constraints;
    374370        #endif
  • issm/trunk/src/c/modules/ConstraintsStatex/ThermalConstraintsState.cpp

    r12330 r13975  
    3737
    3838        #ifdef _HAVE_MPI_
    39         MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
    40         MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,MPI_COMM_WORLD);               
     39        MPI_Reduce (&num_unstable_constraints,&sum_num_unstable_constraints,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
     40        MPI_Bcast(&sum_num_unstable_constraints,1,MPI_INT,0,IssmComm::GetComm());               
    4141        num_unstable_constraints=sum_num_unstable_constraints;
    4242        #endif
  • issm/trunk/src/c/modules/ConstraintsStatex/ThermalIsPresent.cpp

    r12330 r13975  
    2727                }
    2828        }
    29        
     29
    3030        #ifdef _HAVE_MPI_
    31         MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
    32         MPI_Bcast(&mpi_found,1,MPI_INT,0,MPI_COMM_WORLD);               
     31        MPI_Reduce (&found,&mpi_found,1,MPI_INT,MPI_SUM,0,IssmComm::GetComm() );
     32        MPI_Bcast(&mpi_found,1,MPI_INT,0,IssmComm::GetComm());               
    3333        found=mpi_found;
    3434        #endif
  • issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.cpp

    r13395 r13975  
    88#endif
    99
    10 
    1110#include "./ContourToMeshx.h"
    1211
    1312int ContourToMeshx(SeqVec<double>** pin_nod,SeqVec<double>** pin_elem, double* index, double* x, double* y,DataSet* contours,char* interptype,int nel,int nods, int edgevalue) {
    14 
    15         int noerr=1;
    16         int i;
    17         int m,n;
    1813
    1914        /*Contour:*/
     
    2722        num=_NUMTHREADS_;
    2823        #endif
    29 
    3024
    3125        /*output: */
     
    5448        /*Take care of the case where an element interpolation has been requested: */
    5549        if ((strcmp(interptype,"element")==0) || (strcmp(interptype,"element and node")==0)){
    56                 for (n=0;n<nel;n++){
     50                for(int n=0;n<nel;n++){
    5751                        if ( (in_nod_serial[ (int)*(index+3*n+0) -1] == 1) && (in_nod_serial[ (int)*(index+3*n+1) -1] == 1) && (in_nod_serial[ (int)*(index+3*n+2) -1] == 1) ){
    5852                                value=1; in_elem->SetValue(n,value,INS_VAL);
     
    7165        xDelete<double>(in_nod_serial);
    7266
    73         return noerr;
     67        return 1;
    7468}
  • issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshx.h

    r13395 r13975  
    22        ContourToMeshx.h
    33*/
    4 
    54
    65#ifndef _CONTOURTOMESHX_H
     
    2221} ContourToMeshxThreadStruct;
    2322
    24 
    2523/* local prototypes: */
    2624int ContourToMeshx(SeqVec<double>** pin_nods,SeqVec<double>** pin_elem, double* index, double* x, double* y,DataSet* contours,char* interptype,int nel,int nods, int edgevalue);
  • issm/trunk/src/c/modules/ContourToMeshx/ContourToMeshxt.cpp

    r13395 r13975  
    1212
    1313void* ContourToMeshxt(void* vpthread_handle){
    14        
     14
    1515        int noerr=1;
    1616
  • issm/trunk/src/c/modules/ContourToNodesx/ContourToNodesx.cpp

    r13395 r13975  
    77
    88        int i;
    9         int m,n;
    109
    1110        /*Contour:*/
     
    1413        double*  xc=NULL;
    1514        double*  yc=NULL;
    16         double   value;
    1715
    1816        /*output: */
     
    3432        /*Assign output pointers: */
    3533        *pflags=flags;
    36        
    3734        return 1;
    3835}
     
    4037int ContourToNodesx(SeqVec<IssmPDouble>** pflags,double* x, double* y, int nods, DataSet* contours, int edgevalue){
    4138
    42         int i;
    43         int m,n;
    44 
    4539        /*Contour:*/
    4640        Contour<IssmPDouble>* contouri=NULL;
    47         int      numnodes;
    4841        double*  xc=NULL;
    4942        double*  yc=NULL;
    50         double   value;
    5143
    5244        /*output: */
     
    5648        /*Loop through all contours: */
    5749        if(contours){
    58                 for (i=0;i<contours->Size();i++){
     50                for(int i=0;i<contours->Size();i++){
    5951                        Contour<IssmPDouble>* contour=(Contour<IssmPDouble>*)contours->GetObjectByOffset(i);
    6052                        IsInPoly(flags,contour->x,contour->y,contour->nods,x,y,0,nods,edgevalue);
  • issm/trunk/src/c/modules/ControlInputScaleGradientx/ControlInputScaleGradientx.cpp

    r13395 r13975  
    1616        IssmDouble *scalar_list = NULL;
    1717        IssmDouble  scalar;
    18 
    1918
    2019        /*Retrieve some parameters*/
  • issm/trunk/src/c/modules/CreateNodalConstraintsx/CreateNodalConstraintsx.cpp

    r13395 r13975  
    1212void CreateNodalConstraintsx( Vector<IssmDouble>** pys, Nodes* nodes,int configuration_type){
    1313
    14         int i;
    15        
    16         /*intermediary: */
    17         int  numberofdofs;
     14        bool  oldalloc  = false;
    1815
    1916        /*output: */
     
    2118
    2219        /*figure out how many dofs we have: */
    23         numberofdofs=nodes->NumberOfDofs(configuration_type,SsetEnum);
     20        int ssize=nodes->NumberOfDofs(configuration_type,SsetEnum);
     21        int slocalsize = nodes->NumberOfDofsLocal(configuration_type,SsetEnum);
    2422
    2523        /*allocate:*/
    26         ys=new Vector<IssmDouble>(numberofdofs);
     24        if(oldalloc)
     25         ys=new Vector<IssmDouble>(ssize);
     26        else
     27         ys=new Vector<IssmDouble>(slocalsize,ssize);
    2728
    2829        /*go through all nodes, and for the ones corresponding to this configuration_type, fill the
    2930         * constraints vector with the constraint values: */
    30         for (i=0;i<nodes->Size();i++){
     31        for(int i=0;i<nodes->Size();i++){
    3132                Node* node=(Node*)nodes->GetObjectByOffset(i);
    3233                if (node->InAnalysis(configuration_type)){
  • issm/trunk/src/c/modules/Delta18oParameterizationx/Delta18oParameterizationx.cpp

    r13395 r13975  
    1515  int    i;
    1616  Element* element = NULL;
    17  
     17
    1818  /*Compute temperature and precipitation fields: */
    1919  for(i=0;i<elements->Size();i++){
    20     element=(Element*)elements->GetObjectByOffset(i);
     20    element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2121    element->Delta18oParameterization();
    2222  } 
  • issm/trunk/src/c/modules/DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.cpp

    r13395 r13975  
    2222        /*Compute Misfit: */
    2323        for (i=0;i<elements->Size();i++){
    24                 element=(Element*)elements->GetObjectByOffset(i);
     24                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2525                J+=element->DragCoefficientAbsGradient(process_units,weight_index);
    2626        }
     
    2828        /*Sum all J from all cpus of the cluster:*/
    2929        #ifdef _HAVE_MPI_
    30         MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
    31         MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
     30        MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
     31        MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
    3232        J=J_sum;
    3333        #endif
  • issm/trunk/src/c/modules/ElementConnectivityx/ElementConnectivityx.cpp

    r12706 r13975  
    4141         * Once we get the neighbouring elements, figure out if they share a segment with the current element. If so,
    4242         * plug them in the connectivity, unless they are already there.: */
    43        
     43
    4444        for(n=0;n<nel;n++){
    4545
     
    4747
    4848                for(i=0;i<3;i++){
    49                
     49
    5050                        node=(int)*(elements+n*3+i); //already matlab indexed, elements comes directly from the workspace.
    5151                        index=node-1;
     
    5858                                connectedelement=*(nodeconnectivity+width*index+j);
    5959                                connectedelementindex=(int)(connectedelement-1); //go from matlab indexing to c indexing.
    60                                
     60
    6161                                if(hascommondedge(elements+n*3+0,elements+connectedelementindex*3+0)){
    6262                                        /*Ok, this connected element has a commond edge  with element, plug it into elementconnectivity, unless
     
    8080        *pelementconnectivity=elementconnectivity;
    8181}
    82                                
    8382
    8483int hascommondedge(double* element1,double* element2){
  • issm/trunk/src/c/modules/ElementConnectivityx/ElementConnectivityx.h

    r1105 r13975  
    1010
    1111#endif  /* _ELEMENTCONNECTIVITYX_H */
    12 
  • issm/trunk/src/c/modules/EnumToStringx/EnumToStringx.cpp

    r13395 r13975  
    1818
    1919                case AutodiffIsautodiffEnum : return "AutodiffIsautodiff";
    20                 case AutodiffDependentsEnum : return "AutodiffDependents";
    2120                case AutodiffNumDependentsEnum : return "AutodiffNumDependents";
    22                 case AutodiffIndependentsEnum : return "AutodiffIndependents";
     21                case AutodiffNumDependentObjectsEnum : return "AutodiffNumDependentObjects";
     22                case AutodiffDependentObjectNamesEnum : return "AutodiffDependentObjectNames";
     23                case AutodiffDependentObjectTypesEnum : return "AutodiffDependentObjectTypes";
     24                case AutodiffDependentObjectIndicesEnum : return "AutodiffDependentObjectIndices";
     25                case AutodiffDependentObjectsEnum : return "AutodiffDependentObjects";
    2326                case AutodiffNumIndependentsEnum : return "AutodiffNumIndependents";
     27                case AutodiffNumIndependentObjectsEnum : return "AutodiffNumIndependentObjects";
     28                case AutodiffIndependentObjectNamesEnum : return "AutodiffIndependentObjectNames";
     29                case AutodiffIndependentObjectTypesEnum : return "AutodiffIndependentObjectTypes";
     30                case AutodiffIndependentObjectsEnum : return "AutodiffIndependentObjects";
    2431                case AutodiffJacobianEnum : return "AutodiffJacobian";
    2532                case AutodiffXpEnum : return "AutodiffXp";
    26                 case AutodiffFosForwardOutputEnum : return "AutodiffFosForwardOutput";
     33                case AutodiffDriverEnum : return "AutodiffDriver";
     34                case AutodiffFosForwardIndexEnum : return "AutodiffFosForwardIndex";
     35                case AutodiffFovForwardIndicesEnum : return "AutodiffFovForwardIndices";
     36                case AutodiffFosReverseIndexEnum : return "AutodiffFosReverseIndex";
     37                case AutodiffMassFluxSegmentsPresentEnum : return "AutodiffMassFluxSegmentsPresent";
     38                case AutodiffKeepEnum : return "AutodiffKeep";
    2739                case BalancethicknessSpcthicknessEnum : return "BalancethicknessSpcthickness";
    2840                case BalancethicknessStabilizationEnum : return "BalancethicknessStabilization";
     
    3648                case ConstantsReferencetemperatureEnum : return "ConstantsReferencetemperature";
    3749                case ConstantsYtsEnum : return "ConstantsYts";
     50                case DependentObjectEnum : return "DependentObject";
    3851                case DiagnosticAbstolEnum : return "DiagnosticAbstol";
    3952                case DiagnosticIcefrontEnum : return "DiagnosticIcefront";
     
    7588                case HydrologySpcwatercolumnEnum : return "HydrologySpcwatercolumn";
    7689                case HydrologyStabilizationEnum : return "HydrologyStabilization";
     90                case IndependentObjectEnum : return "IndependentObject";
    7791                case InversionControlParametersEnum : return "InversionControlParameters";
    7892                case InversionCostFunctionEnum : return "InversionCostFunction";
     
    148162                case PrognosticStabilizationEnum : return "PrognosticStabilization";
    149163                case PrognosticVertexPairingEnum : return "PrognosticVertexPairing";
     164                case PrognosticNumRequestedOutputsEnum : return "PrognosticNumRequestedOutputs";
     165                case PrognosticRequestedOutputsEnum : return "PrognosticRequestedOutputs";
    150166                case QmuIsdakotaEnum : return "QmuIsdakota";
    151                 case QmuMassFluxSegmentsEnum : return "QmuMassFluxSegments";
     167                case MassFluxSegmentsEnum : return "MassFluxSegments";
     168                case MassFluxSegmentsPresentEnum : return "MassFluxSegmentsPresent";
     169                case QmuMassFluxSegmentsPresentEnum : return "QmuMassFluxSegmentsPresent";
    152170                case QmuNumberofpartitionsEnum : return "QmuNumberofpartitions";
    153171                case QmuNumberofresponsesEnum : return "QmuNumberofresponses";
     
    184202                case SurfaceforcingsMonthlytemperaturesEnum : return "SurfaceforcingsMonthlytemperatures";
    185203                case SurfaceforcingsHcEnum : return "SurfaceforcingsHc";
     204                case SurfaceforcingsHrefEnum : return "SurfaceforcingsHref";
     205                case SurfaceforcingsSmbrefEnum : return "SurfaceforcingsSmbref";
    186206                case SurfaceforcingsSmbPosMaxEnum : return "SurfaceforcingsSmbPosMax";
    187207                case SurfaceforcingsSmbPosMinEnum : return "SurfaceforcingsSmbPosMin";
     
    270290                case DofIndexingEnum : return "DofIndexing";
    271291                case DoubleInputEnum : return "DoubleInput";
     292                case DataSetParamEnum : return "DataSetParam";
    272293                case DoubleMatArrayParamEnum : return "DoubleMatArrayParam";
    273294                case DoubleMatParamEnum : return "DoubleMatParam";
     
    299320                case PentaEnum : return "Penta";
    300321                case PentaP1InputEnum : return "PentaP1Input";
     322                case ProfilerEnum : return "Profiler";
    301323                case MatrixParamEnum : return "MatrixParam";
    302324                case VectorParamEnum : return "VectorParam";
     
    467489                case OldGradientEnum : return "OldGradient";
    468490                case OutputFilePointerEnum : return "OutputFilePointer";
     491                case OutputFileNameEnum : return "OutputFileName";
     492                case LockFileNameEnum : return "LockFileName";
    469493                case PetscOptionsAnalysesEnum : return "PetscOptionsAnalyses";
    470494                case PetscOptionsStringsEnum : return "PetscOptionsStrings";
  • issm/trunk/src/c/modules/Exp2Kmlx/Exp2Kmlx.cpp

    r13395 r13975  
    295295        return(iret);
    296296}
    297 
  • issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.cpp

    r13395 r13975  
    2727        gsize=nodes->NumberOfDofs(configuration_type,GsetEnum);
    2828        if (gsize==0) _error_("Allocating a Vec of size 0 as gsize=0 for configuration: " << EnumToStringx(configuration_type));
    29        
     29
    3030        /*Initialize solution: */
    3131        solution=new Vector<IssmDouble>(gsize);
    32        
     32
    3333        /*Go through elements and plug solution: */
    3434        for (i=0;i<elements->Size();i++){
    35                 element=(Element*)elements->GetObjectByOffset(i);
     35                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    3636                element->GetSolutionFromInputs(solution);
    3737        }
  • issm/trunk/src/c/modules/GetSolutionFromInputsx/GetSolutionFromInputsx.h

    r13395 r13975  
    1313
    1414#endif  /* _GETSOLUTIONFROMINPUTSXX_H */
    15 
  • issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.cpp

    r13395 r13975  
    3737
    3838void GetVectorFromControlInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, const char* data){
    39        
     39
    4040        /*output: */
    4141        IssmDouble* vector=NULL;
    42        
     42
    4343        /*intermediary: */
    4444        Vector<IssmDouble>* vec_vector=NULL;
  • issm/trunk/src/c/modules/GetVectorFromControlInputsx/GetVectorFromControlInputsx.h

    r13395 r13975  
    1313
    1414#endif  /* _GETVECTORFROMCONTROLINPUTSXX_H */
    15 
  • issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.cpp

    r13395 r13975  
    2121                /*Look up in elements*/
    2222                for(i=0;i<elements->Size();i++){
    23                         Element* element=(Element*)elements->GetObjectByOffset(i);
     23                        Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2424                        element->GetVectorFromInputs(vector,name);
    2525                }
     
    4242
    4343void GetVectorFromInputsx( IssmDouble** pvector, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters, int name, int type){
    44        
     44
    4545        /*output: */
    4646        IssmDouble* vector=NULL;
    47        
     47
    4848        /*intermediary: */
    4949        Vector<IssmDouble>* vec_vector=NULL;
  • issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h

    r13395 r13975  
    1313
    1414#endif  /* _GETVECTORFROMINPUTSXX_H */
    15 
  • issm/trunk/src/c/modules/Gradjx/Gradjx.cpp

    r13395 r13975  
    1919        Vector<IssmDouble>  *gradient      = NULL;
    2020        Vector<IssmDouble> **gradient_list = NULL;
    21        
     21
    2222        /*retrieve some parameters: */
    2323        parameters->FindParam(&num_controls,InversionNumControlParametersEnum);   _assert_(num_controls);
  • issm/trunk/src/c/modules/GroundinglineMigrationx/GroundinglineMigrationx.cpp

    r13395 r13975  
    1919        Vector<IssmDouble>*      vec_old_floatingice              = NULL;
    2020        Element* element                          = NULL;
    21        
     21
    2222        if(VerboseModule()) _pprintLine_("   Migrating grounding line");
    23        
     23
    2424        /*retrieve parameters: */
    2525        parameters->FindParam(&migration_style,GroundinglineMigrationEnum);
     
    4343        /*Migrate grounding line : */
    4444        for(i=0;i<elements->Size();i++){
    45                 element=(Element*)elements->GetObjectByOffset(i);
     45                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    4646                element->MigrateGroundingLine(old_floatingice,vertices_ungrounding);
    4747        }
     
    9595        /*Fill vector vertices_potentially_floating: */
    9696        for(i=0;i<elements->Size();i++){
    97                 element=(Element*)elements->GetObjectByOffset(i);
     97                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    9898                element->PotentialSheetUngrounding(vec_vertices_potentially_ungrounding);
    9999        }
     
    121121        Element* element                               = NULL;
    122122
    123 
    124123        /*recover parameters: */
    125124        parameters->FindParam(&analysis_type,AnalysisTypeEnum);
     
    132131        nflipped=1; //bootstrap
    133132        while(nflipped){
    134                
     133
    135134                /*Vector of size number of elements*/
    136135                vec_elements_neighboring_floatingice=new Vector<IssmDouble>(elements->NumberOfElements(),true);
     
    138137                /*Figure out if any of the nodes of the element will be floating -> elements neighbouting the floating ice*/
    139138                for(i=0;i<elements->Size();i++){
    140                         element=(Element*)elements->GetObjectByOffset(i);
     139                        element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    141140                        vec_elements_neighboring_floatingice->SetValue(element->Sid(),element->IsNodeOnShelfFromFlags(nodes_on_floatingice)?1.0:0.0,INS_VAL);
    142141                }
     
    149148                local_nflipped=0;
    150149                for(i=0;i<elements->Size();i++){
    151                         element=(Element*)elements->GetObjectByOffset(i);
     150                        element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    152151                        if(reCast<int,IssmDouble>(elements_neighboring_floatingce[element->Sid()])){
    153152                                local_nflipped+=element->UpdatePotentialSheetUngrounding(vertices_potentially_ungrounding,vec_nodes_on_floatingice,nodes_on_floatingice);
     
    155154                }
    156155                vec_nodes_on_floatingice->Assemble();
    157                
     156
    158157                #ifdef _HAVE_MPI_
    159                 MPI_Allreduce(&local_nflipped,&nflipped,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
     158                MPI_Allreduce(&local_nflipped,&nflipped,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
    160159                if(VerboseConvergence()) _pprintLine_("   Additional number of vertices allowed to unground: " << nflipped);
    161160                #else
  • issm/trunk/src/c/modules/HoleFillerx/HoleFillerx.cpp

    r12706 r13975  
    1010
    1111int HoleFillerx(double** pimageout,double* image, int lines,int samps,int smooth){
    12        
    13         FILE                    *fp1;
    14         unsigned long   filesize;
     12
    1513        long                    infinit;
    1614        double          temp;
    17         long                    i, j, k, l, ii, jj, bytes;
     15        long                    i, j, k, l, ii, jj;
    1816        long                    iii, jjj;
    19         long                    test, prevlines, prevpix, test1, test2, thresh,counter;
    20         long                    bell, cycles, leftovers;
    21         float                   howlong;
     17        long                    test;
    2218        float                   nsteps, ssteps, wsteps, esteps;
    2319        float                   nwsteps, nesteps, swsteps, sesteps;
     
    2925        float                   ssw, wsw, wnw, nnw;     
    3026        float                   sum;
    31        
     27
    3228        time_t                  t1, t2;
    3329
     
    3935        double*         image4=NULL;
    4036
    41         /*Added to original routine: */
    42         int             imageoutsize;
    43 
    4437         /*^^^^^^^^^^^^^  Remove pixels close to the holes ^^^^^^^^^^^^^*/
    4538        image2 = xNew<double>(lines*samps);
    4639        memcpy(image2,image,lines*samps*sizeof(double));
    47        
     40
    4841        for ( i = 0; i < lines; i++ ){
    4942                for ( j = 0; j < samps; j++ ){
     
    8477
    8578        again2:
    86        
     79
    8780        #ifdef _DEBUG2_
    8881                counter=0;
     
    9992                fflush( stdout );
    10093        #endif
    101        
     94
    10295        afterfirst2:
    10396
     
    128121
    129122                        /* For void edge pixels: */                     
    130                        
     123
    131124                        nsteps = 0.0; ssteps = 0.0; esteps = 0.0; wsteps = 0.0;
    132125                        nwsteps = 0.0; nesteps = 0.0; swsteps = 0.0; sesteps = 0.0;
     
    139132                        ssw = 0.0; wsw = 0.0; wnw = 0.0; nnw = 0.0;
    140133
    141 
    142134/** NSEW **/
    143135                        for ( ii = i - 1; ii >= 0; ii-- ){   /* North */
     
    150142                                if ( *(image2+ii*samps+j) != 0 ){ south = *(image2+ii*samps+j); ssteps = ii - i; break;}
    151143                        }
    152                                
     144
    153145                        for ( jj = j - 1; jj >= 0; jj-- ){   /* West */
    154146                                if ( jj <= 0 ) { west = 0; wsteps = 0; break;}
    155147                                if ( *(image2+i*samps+jj) != 0 ){ west = *(image2+i*samps+jj); wsteps = j - jj; break;}
    156148                        }
    157                                
     149
    158150                        for ( jj = j + 1; jj < samps; jj++ ){ /* East */
    159151                                if ( jj >= samps-1 ){ east = 0; esteps = 0; break;}
     
    161153                        }
    162154
    163                                
    164155/** Diagonals  **/                                             
    165156                        /* Southeast */
     
    169160                                if ( *(image2+ii*samps+jj) != 0 ){ se = *(image2+ii*samps+jj); sesteps = 1.4142 * k; break;}
    170161                        }
    171                        
     162
    172163                        /* Northeast */
    173164                        for ( k = 1; k < infinit; k++ ){
     
    176167                                if ( *(image2+ii*samps+jj) != 0 ){ ne = *(image2+ii*samps+jj); nesteps = 1.4142 * k; break;}
    177168                        }
    178                        
     169
    179170                        /* Northwest */
    180171                        for ( k = 1; k < infinit; k++ ){
     
    183174                                if ( *(image2+ii*samps+jj) != 0 ){ nw = *(image2+ii*samps+jj); nwsteps = 1.4142 * k; break;}
    184175                        }
    185                        
     176
    186177                        /* Southwest */
    187178                        for ( k = 1; k < infinit; k++ ){
     
    198189                                if ( *(image2+ii*samps+jj) != 0 ){ nne = *(image2+ii*samps+jj); nnesteps = 2.2361 * k; break;}
    199190                        }
    200                        
     191
    201192                        /* ENE */
    202193                        for ( k = 1; k < infinit; k++ ){
     
    205196                                if ( *(image2+ii*samps+jj) != 0 ){ ene = *(image2+ii*samps+jj); enesteps = 2.2361 * k; break;}
    206197                        }
    207                        
     198
    208199                        /* ESE */
    209200                        for ( k = 1; k < infinit; k++ ){
     
    212203                                if ( *(image2+ii*samps+jj) != 0 ){ ese = *(image2+ii*samps+jj); esesteps = 2.2361 * k; break;}
    213204                        }
    214                        
     205
    215206                        /* SSE */
    216207                        for ( k = 1; k < infinit; k++ ){
     
    226217                                if ( *(image2+ii*samps+jj) != 0 ){ ssw = *(image2+ii*samps+jj); sswsteps = 2.2361 * k; break;}
    227218                        }
    228                        
     219
    229220                        /* WSW */
    230221                        for ( k = 1; k < infinit; k++ ){
     
    233224                                if ( *(image2+ii*samps+jj) != 0 ){ wsw = *(image2+ii*samps+jj); wswsteps = 2.2361 * k; break;}
    234225                        }
    235                        
     226
    236227                        /* WNW */
    237228                        for ( k = 1; k < infinit; k++ ){
     
    240231                                if ( *(image2+ii*samps+jj) != 0 ){ wnw = *(image2+ii*samps+jj); wnwsteps = 2.2361 * k; break;}
    241232                        }
    242                        
     233
    243234                        /* NNW */
    244235                        for ( k = 1; k < infinit; k++ ){
     
    247238                                if ( *(image2+ii*samps+jj) != 0 ){ nnw = *(image2+ii*samps+jj); nnwsteps = 2.2361 * k; break;}
    248239                        }
    249                        
     240
    250241                        elev = 0; range = 0;
    251242/*NSEW*/                       
     
    259250                        if ( swsteps > 0.5 ){ elev +=    sw / swsteps; range +=  1.00 / swsteps;}
    260251                        if ( sesteps > 0.5 ){ elev +=    se / sesteps; range +=  1.00 / sesteps;}
    261                        
     252
    262253/*Other 8*/
    263254                        if ( nnesteps > 0.5 ){ elev += nne / nnesteps; range +=  1.00 / nnesteps;}
     
    269260                        if ( wnwsteps > 0.5 ){ elev += wnw / wnwsteps; range +=  1.00 / wnwsteps;}
    270261                        if ( nnwsteps > 0.5 ){ elev += nnw / nnwsteps; range +=  1.00 / nnwsteps;}
    271                                                                        
     262
    272263                        //temp = ( elev / range ) + 0.5 ;
    273264                        temp = ( elev / range );
     
    275266                        //if ( temp > 10000 ) temp = 10000;
    276267                        //if ( temp <     0 ) temp =     0;
    277                        
     268
    278269                        #ifdef _DEBUG2_
    279270                                //_printLine_(temp << " " << elev << " " << range << " ");
     
    284275        }
    285276
    286 
    287 
    288277        for ( i = 0; i < lines; i++ ){
    289278                for ( j = 0; j < samps; j++ ){
     
    292281        }
    293282
    294 
    295283        for ( i = 0; i < lines; i++ ){
    296284                for ( j = 0; j < samps; j++ ){
     
    298286                }
    299287        }
    300        
     288
    301289        if ( smooth == 0 ) goto there2;         
    302                
    303                
     290
    304291/************************ SMOOTH THE RESULT ***********************/           
    305                
     292
    306293        image4 = xNew<double>(lines*samps);
    307294        memcpy(image4,image3,lines*samps*sizeof(double));
    308 
    309295
    310296        for ( i = 0; i < lines; i++ ) {
    311297                for ( j = 0; j < samps; j++ ) {
    312298                        if ( *(image4+i*samps+j) != 0 ) { *(image3+i*samps+j) = *(image2+i*samps+j) ; continue; }
    313 
    314299
    315300                        for ( k = 1; k < infinit; k++ ) { /* Find the smallest box size with data */
     
    324309                                }
    325310                        }
    326                
     311
    327312                        k_nowset:
    328313                        k = k / 4; if ( k < 1 ) k = 1; /* Errrrr.  Make it fourth size */
     
    343328        }
    344329
    345                
    346330there2:         
    347 
    348331
    349332        /*Allocate output image: */
     
    352335
    353336        time(&t2);     
    354        
     337
    355338        #ifdef _DEBUG2_
    356339                _printString_( "\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b" );
     
    358341                printf ( "\n");
    359342        #endif
    360        
     343
    361344        end:
    362345
  • issm/trunk/src/c/modules/HoleFillerx/HoleFillerx.h

    r3110 r13975  
    22        HoleFillerx.h
    33*/
    4 
    54
    65#ifndef HOLEFILLERX_H
     
    1211/* local prototypes: */
    1312int HoleFillerx(double** pimageout,double* imagein, int lines,int samp,int smooth);
    14        
     13
    1514#endif /* HOLEFILLERX_H */
    16 
  • issm/trunk/src/c/modules/InputArtificialNoisex/InputArtificialNoisex.cpp

    r12706 r13975  
    1515        /*Update elements, nodes, loads and materials from inputs: */
    1616        for(i=0;i<elements->Size();i++){
    17                 Element* element=(Element*)elements->GetObjectByOffset(i);
     17                Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    1818                element->InputArtificialNoise(enum_name,min,max);
    1919        }
  • issm/trunk/src/c/modules/InputControlUpdatex/InputControlUpdatex.cpp

    r13395 r13975  
    1313        /*Go through elemnets, and ask to carry out the operation on inputs: */
    1414        for(int i=0;i<elements->Size();i++){
    15                 Element* element=(Element*)elements->GetObjectByOffset(i);
     15                Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    1616                element->InputControlUpdate(scalar,save_parameter);
    1717        }
  • issm/trunk/src/c/modules/InputConvergencex/InputConvergencex.cpp

    r12706 r13975  
    2424        /*Go through elements, and ask them to do the job: */
    2525        for(i=0;i<elements->Size();i++){
    26                 element=(Element*)elements->GetObjectByOffset(i);
     26                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2727                converged=element->InputConvergence(eps,enums,num_enums,criterionenums,criterionvalues,num_criterionenums);
    2828                if(!converged) num_notconverged++;
     
    3131        /*In parallel, we need to gather the converged status: */
    3232        #ifdef _HAVE_MPI_
    33         MPI_Allreduce ( (void*)&num_notconverged,(void*)&total_notconverged,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
     33        MPI_Allreduce ( (void*)&num_notconverged,(void*)&total_notconverged,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
    3434        num_notconverged=total_notconverged;
    3535        #endif
  • issm/trunk/src/c/modules/InputConvergencex/InputConvergencex.h

    r12706 r13975  
    1111
    1212#endif  /* _INPUTCONVERGENCEX_H */
    13 
  • issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.cpp

    r4967 r13975  
    1010
    1111void InputDuplicatex(Elements* elements,Nodes* nodes,Vertices* vertices,Loads* loads,Materials* materials,Parameters* parameters,int original_enum, int new_enum){
    12        
     12
    1313        /*Go through elemnets, and ask to reinitialie the input: */
    1414        int      i;
    1515        for(i=0;i<elements->Size();i++){
    16                 Element* element=(Element*)elements->GetObjectByOffset(i);
     16                Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    1717                element->InputDuplicate(original_enum,new_enum);
    1818        }
  • issm/trunk/src/c/modules/InputDuplicatex/InputDuplicatex.h

    r4236 r13975  
    1212
    1313#endif  /* _INPUTDUPLICATEX_H */
    14 
  • issm/trunk/src/c/modules/InputScalex/InputScalex.cpp

    r12706 r13975  
    1616        /*Go through elemnets, and ask to reinitialie the input: */
    1717        for(i=0;i<elements->Size();i++){
    18                 Element* element=(Element*)elements->GetObjectByOffset(i);
     18                Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    1919                element->InputScale(enum_type,scale_factor);
    2020        }
  • issm/trunk/src/c/modules/InputScalex/InputScalex.h

    r12706 r13975  
    1212
    1313#endif  /* _SCALEINPUTX_H */
    14 
  • issm/trunk/src/c/modules/InputToResultx/InputToResultx.cpp

    r12706 r13975  
    2323        for(int i=0;i<elements->Size();i++){
    2424
    25                 element=(Element*)elements->GetObjectByOffset(i);
     25                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2626                element->InputToResult(enum_type,step,time);
    2727        }
  • issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.cpp

    r12706 r13975  
    1515        /*Elements and loads drive the update: */
    1616        for(i=0;i<elements->Size();i++){
    17                 Element* element=(Element*)elements->GetObjectByOffset(i);
     17                Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    1818                element->InputUpdateFromConstant(constant,name);
    1919        }
     
    2323                load->InputUpdateFromConstant(constant,name);
    2424        }
    25        
     25
    2626        for(i=0;i<materials->Size();i++){
    2727                Material* material=(Material*)materials->GetObjectByOffset(i);
     
    3030}
    3131void InputUpdateFromConstantx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int    constant, int name){
    32        
     32
    3333        int i;
    3434
    3535        /*Elements and loads drive the update: */
    3636        for(i=0;i<elements->Size();i++){
    37                 Element* element=(Element*)elements->GetObjectByOffset(i);
     37                Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    3838                element->InputUpdateFromConstant(constant,name);
    3939        }
     
    4343                load->InputUpdateFromConstant(constant,name);
    4444        }
    45        
     45
    4646        for(i=0;i<materials->Size();i++){
    4747                Material* material=(Material*)materials->GetObjectByOffset(i);
     
    5555        /*Elements and loads drive the update: */
    5656        for(i=0;i<elements->Size();i++){
    57                 Element* element=(Element*)elements->GetObjectByOffset(i);
     57                Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    5858                element->InputUpdateFromConstant(constant,name);
    5959        }
     
    6363                load->InputUpdateFromConstant(constant,name);
    6464        }
    65        
     65
    6666        for(i=0;i<materials->Size();i++){
    6767                Material* material=(Material*)materials->GetObjectByOffset(i);
  • issm/trunk/src/c/modules/InputUpdateFromConstantx/InputUpdateFromConstantx.h

    r13395 r13975  
    1515
    1616#endif  /* _UPDATEINPUTSFROMCONSTANTXX_H */
    17 
  • issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.cpp

    r13395 r13975  
    1414        int     i,j,k,l;
    1515        int     dummy;
    16        
     16
    1717        int     numberofvertices;
    1818        int     nrows;
     
    3535
    3636        for(i=0;i<numvariables;i++){
    37        
     37
    3838                descriptor=variables_descriptors[i];
    3939
    4040                /*From descriptor, figure out if the variable is scaled, indexed, nodal, or just a simple variable: */
    4141                if (strncmp(descriptor,"scaled_",7)==0){
    42                        
     42
    4343                        /*Variable is scaled. Determine root name of variable (ex: scaled_DragCoefficient_1 -> DragCoefficient). Allocate distributed_values and fill the
    4444                         * distributed_values with the next npart variables: */
    45                        
     45
    4646                        //strcpy(root,strstr(descriptor,"_")+1); *strstr(root,"_")='\0';
    4747                        memcpy(root,strstr(descriptor,"_")+1,(strlen(strstr(descriptor,"_")+1)+1)*sizeof(char));
    4848                        *strstr(root,"_")='\0';
    49 
    5049
    5150                        distributed_values=xNew<double>(npart);
     
    6867
    6968                        #ifdef _DEBUG_
    70                                 PetscSynchronizedPrintf(MPI_COMM_WORLD,"Parameter matrix:");
    71                                 PetscSynchronizedFlush(MPI_COMM_WORLD);
     69                                PetscSynchronizedPrintf(IssmComm::GetComm(),"Parameter matrix:");
     70                                PetscSynchronizedFlush(IssmComm::GetComm());
    7271                                for(l=0;l<ncols;l++){
    73                                         PetscSynchronizedPrintf(MPI_COMM_WORLD," time %i\n",l);
    74                                         PetscSynchronizedFlush(MPI_COMM_WORLD);
     72                                        PetscSynchronizedPrintf(IssmComm::GetComm()," time %i\n",l);
     73                                        PetscSynchronizedFlush(IssmComm::GetComm());
    7574
    7675                                        for(k=0;k<numberofvertices;k++){
    77                                                 PetscSynchronizedPrintf(MPI_COMM_WORLD," node %i value %g\n",k+1,*(parameter+k*ncols+l));
    78                                                 PetscSynchronizedFlush(MPI_COMM_WORLD);
     76                                                PetscSynchronizedPrintf(IssmComm::GetComm()," node %i value %g\n",k+1,*(parameter+k*ncols+l));
     77                                                PetscSynchronizedFlush(IssmComm::GetComm());
    7978                                        }
    8079                                }
    81                                 PetscSynchronizedPrintf(MPI_COMM_WORLD," descriptor: %s root %s enum: %i\n",descriptor,root,StringToEnumx(root));
    82                                 PetscSynchronizedFlush(MPI_COMM_WORLD);
     80                                PetscSynchronizedPrintf(IssmComm::GetComm()," descriptor: %s root %s enum: %i\n",descriptor,root,StringToEnumx(root));
     81                                PetscSynchronizedFlush(IssmComm::GetComm());
    8382                        #endif
    84                          
    8583
    8684                        /*Update inputs using the parameter matrix: */
  • issm/trunk/src/c/modules/InputUpdateFromDakotax/InputUpdateFromDakotax.h

    r13395 r13975  
    1212
    1313#endif  /* _INPUTUPDATEFROMDAKOTAXX_H */
    14 
  • issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.cpp

    r10576 r13975  
    2222                /*Update elements, nodes, loads and materials from inputs: */
    2323                for(i=0;i<elements->Size();i++){
    24                         Element* element=(Element*)elements->GetObjectByOffset(i);
     24                        Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2525                        element->InputUpdateFromMatrixDakota(matrix,nrows,ncols,name,type);
    2626                }
  • issm/trunk/src/c/modules/InputUpdateFromMatrixDakotax/InputUpdateFromMatrixDakotax.h

    r13395 r13975  
    1313
    1414#endif  /* _UPDATEINPUTSFROMMATRIXDAKOTAXX_H */
    15 
  • issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.cpp

    r13395 r13975  
    2323}
    2424
    25 
    2625void InputUpdateFromSolutionx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* solution){
    2726
     
    3231        /*Elements drive the update: */
    3332        for (i=0;i<elements->Size();i++){
    34                 element=(Element*)elements->GetObjectByOffset(i);
     33                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    3534                element->InputUpdateFromSolution(solution);
    3635        }
  • issm/trunk/src/c/modules/InputUpdateFromSolutionx/InputUpdateFromSolutionx.h

    r13395 r13975  
    1818
    1919#endif  /* _UPDATEINPUTSFROMSOLUTIONXX_H */
    20 
  • issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.cpp

    r13395 r13975  
    2121}
    2222
    23        
    2423void InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,double* vector, int name, int type){
    2524
     
    2827        /*Update elements, nodes, loads and materials from inputs: */
    2928        for(i=0;i<elements->Size();i++){
    30                 Element* element=(Element*)elements->GetObjectByOffset(i);
     29                Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    3130                element->InputUpdateFromVectorDakota(vector,name,type);
    3231        }
     
    4645
    4746void InputUpdateFromVectorDakotax( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int* vector, int name, int type){
    48        
     47
    4948        int i;
    5049
    5150        /*Update elements, nodes, loads and materials from inputs: */
    5251        for(i=0;i<elements->Size();i++){
    53                 Element* element=(Element*)elements->GetObjectByOffset(i);
     52                Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    5453                element->InputUpdateFromVectorDakota(vector,name,type);
    5554        }
     
    7473        /*Update elements, nodes, loads and materials from inputs: */
    7574        for(i=0;i<elements->Size();i++){
    76                 Element* element=(Element*)elements->GetObjectByOffset(i);
     75                Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    7776                element->InputUpdateFromVectorDakota(vector,name,type);
    7877        }
  • issm/trunk/src/c/modules/InputUpdateFromVectorDakotax/InputUpdateFromVectorDakotax.h

    r13395 r13975  
    1616
    1717#endif  /* _UPDATEINPUTSFROMVECTORDAKOTAXX_H */
    18 
  • issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.cpp

    r13395 r13975  
    2121}
    2222
    23        
    2423void InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,IssmDouble* vector, int name, int type){
    2524
     
    2827        /*Update elements, nodes, loads and materials from inputs: */
    2928        for(i=0;i<elements->Size();i++){
    30                 Element* element=(Element*)elements->GetObjectByOffset(i);
     29                Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    3130                element->InputUpdateFromVector(vector,name,type);
    3231        }
     
    4645
    4746void InputUpdateFromVectorx( Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,int* vector, int name, int type){
    48        
     47
    4948        int i;
    5049
    5150        /*Update elements, nodes, loads and materials from inputs: */
    5251        for(i=0;i<elements->Size();i++){
    53                 Element* element=(Element*)elements->GetObjectByOffset(i);
     52                Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    5453                element->InputUpdateFromVector(vector,name,type);
    5554        }
     
    7473        /*Update elements, nodes, loads and materials from inputs: */
    7574        for(i=0;i<elements->Size();i++){
    76                 Element* element=(Element*)elements->GetObjectByOffset(i);
     75                Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    7776                element->InputUpdateFromVector(vector,name,type);
    7877        }
  • issm/trunk/src/c/modules/InputUpdateFromVectorx/InputUpdateFromVectorx.h

    r13395 r13975  
    1616
    1717#endif  /* _UPDATEINPUTSFROMVECTORXX_H */
    18 
  • issm/trunk/src/c/modules/InterpFromGridToMeshx/InterpFromGridToMeshx.cpp

    r13395 r13975  
    2121        /*output: */
    2222        SeqVec<IssmPDouble>* data_mesh=NULL;
    23        
     23
    2424        /*Intermediary*/
    2525        double* x=NULL;
    2626        double* y=NULL;
    27         double  x_grid,y_grid;
    2827        int     i;
    2928
     
    312311        _assert_(x2>x1 && y2>y1);
    313312        _assert_(x<=x2 && x>=x1 && y<=y2 && y>=y1);
    314        
     313
    315314        double xm=(x2-x1)/2;
    316315        double ym=(y2-y1)/2;
  • issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.cpp

    r13395 r13975  
    1414                        double* x_prime, double* y_prime, int nods_prime,
    1515                        double* default_values,int num_default_values,Contour<IssmPDouble>** contours,int numcontours){
    16        
     16
    1717        /*Output*/
    1818        SeqVec<IssmPDouble>* data_prime=NULL;
    1919
    2020        /*Intermediary*/
    21         int    i,j;
     21        int    i;
    2222        int    interpolation_type;
    2323        bool   debug;
    24         double area;
    25         double area_1,area_2,area_3;
    26         double data_value;
    2724        double xmin,xmax;
    2825        double ymin,ymax;
  • issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dx.h

    r13395 r13975  
    2929        double              *incontour;
    3030
    31 
    3231} InterpFromMesh2dxThreadStruct;
    3332
  • issm/trunk/src/c/modules/InterpFromMesh2dx/InterpFromMesh2dxt.cpp

    r13395 r13975  
    1818        int                            my_thread   = handle->id;
    1919        int                            num_threads = handle->num;
    20        
     20
    2121        /*recover parameters :*/
    2222        int     interpolation_type      = gate->interpolation_type;
  • issm/trunk/src/c/modules/InterpFromMeshToGridx/InterpFromMeshToGridx.cpp

    r13395 r13975  
    6969                }
    7070        }
    71        
     71
    7272        /*Get extreme coordinates of the grid*/
    7373        if (xflip){
  • issm/trunk/src/c/modules/InterpFromMeshToMesh2dx/InterpFromMeshToMesh2dx.cpp

    r13395 r13975  
    1515int InterpFromMeshToMesh2dx(double** pdata_interp,int* index_data,double* x_data,double* y_data,int nods_data,int nels_data,
    1616                        double* data,int M_data,int N_data,double* x_interp,double* y_interp,int N_interp,Options* options){
    17        
     17
    1818        /*Output*/
    1919        double* data_interp=NULL;
     
    2525        R2     r;
    2626        I2     I;
    27         int    i,j,k;
     27        int    i,j;
    2828        int    it;
    2929        int    i0,i1,i2;
    3030        double areacoord[3];
    3131        double aa,bb;
    32         double data_value;
    3332        Icoor2 dete[3];
    3433
  • issm/trunk/src/c/modules/IoModelToConstraintsx/IoModelToConstraintsx.cpp

    r13395 r13975  
    1111
    1212void IoModelToConstraintsx(Constraints* constraints,IoModel* iomodel,int vector_enum,int analysis_type){
    13        
    1413
    1514        /*intermediary: */
    1615        int     i,j;
    17         bool    transient     = false;
    18 
    19         FILE   *fid           = NULL;
    20         int     code          = 0;
    21         int     vector_layout = 0;
    22         int     counter;
    23         int     nods;
    24         IssmDouble* times=NULL;
    25         IssmDouble* values=NULL;
    26         bool    spcpresent=false;
    27         int     count=0;
    28         int     numberofvertices;
     16        bool        transient        = false;
     17        FILE       *fid              = NULL;
     18        int         code             = 0;
     19        int         vector_layout    = 0;
     20        IssmDouble *times            = NULL;
     21        IssmDouble *values           = NULL;
     22        bool        spcpresent       = false;
     23        int         count            = 0;
     24        int         numberofvertices;
    2925
    3026        /*variables being fetched: */
     
    4844                /*static: just create Constraints objects*/
    4945                count=0;
    50        
     46
    5147                /*Create Constraints from x,y,z: */
    5248                for (i=0;i<numberofvertices;i++){
    53                        
     49
    5450                        /*keep only this partition's nodes:*/
    5551                        if((iomodel->my_vertices[i])){
     
    7874                /*Create constraints from x,y,z: */
    7975                for (i=0;i<numberofvertices;i++){
    80                        
     76
    8177                        /*keep only this partition's nodes:*/
    8278                        if((iomodel->my_vertices[i])){
  • issm/trunk/src/c/modules/KMLFileReadx/KMLFileReadx.cpp

    r12706 r13975  
    6565        return(kfil);
    6666}
    67 
  • issm/trunk/src/c/modules/KMLOverlayx/KMLOverlayx.cpp

    r12706 r13975  
    7979        kdoc=NULL;
    8080
    81 
    8281/*  write kml file  */
    8382
     
    9594        return;
    9695}
    97 
  • issm/trunk/src/c/modules/Kml2Expx/Kml2Expx.cpp

    r13395 r13975  
    2525                         int sgn,double cm,double sp){
    2626
    27         int     i,iret=0;
     27        int     iret=0;
    2828        double  *lat=NULL,*lon=NULL;
    2929
     
    6969        return(iret);
    7070}
    71 
  • issm/trunk/src/c/modules/Krigingx/pKrigingx.cpp

    r13395 r13975  
    1414int pKrigingx(double** ppredictions,double **perror,double* obs_x, double* obs_y, double* obs_list, int obs_length,double* x_interp,double* y_interp,int n_interp,Options* options){
    1515
    16         extern int num_procs;
    17         extern int my_rank;
     16        int num_procs;
     17        int my_rank;
    1818
    1919        /*output*/
     
    2727        Variogram    *variogram    = NULL;
    2828        Observations *observations = NULL;
     29
     30        /*Get my_rank: */
     31        my_rank=IssmComm::GetRank();
     32        num_procs=IssmComm::GetSize();
    2933
    3034        /*Get some Options*/
     
    6468                double *sumpredictions =xNew<double>(n_interp);
    6569                double *sumerror       =xNew<double>(n_interp);
    66                 MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
    67                 MPI_Allreduce(error,sumerror,n_interp,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
     70                MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,IssmComm::GetComm());
     71                MPI_Allreduce(error,sumerror,n_interp,MPI_DOUBLE,MPI_SUM,IssmComm::GetComm());
    6872                xDelete<double>(error); error=sumerror;
    6973                xDelete<double>(predictions); predictions=sumpredictions;
     
    8185#ifdef _HAVE_MPI_
    8286                double *sumpredictions =xNew<double>(n_interp);
    83                 MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
     87                MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,IssmComm::GetComm());
    8488                xDelete<double>(predictions); predictions=sumpredictions;
    8589#endif
     
    98102#ifdef _HAVE_MPI_
    99103                double *sumpredictions =xNew<double>(n_interp);
    100                 MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,MPI_COMM_WORLD);
     104                MPI_Allreduce(predictions,sumpredictions,n_interp,MPI_DOUBLE,MPI_SUM,IssmComm::GetComm());
    101105                xDelete<double>(predictions); predictions=sumpredictions;
    102106#endif
  • issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.cpp

    r13395 r13975  
    4040                VecMergex(ug,uf,nodes,parameters,FsetEnum);
    4141        }
    42        
     42
    4343        /*Merge s set back into g set: */
    4444        if(ssize){
  • issm/trunk/src/c/modules/Mergesolutionfromftogx/Mergesolutionfromftogx.h

    r13395 r13975  
    1212
    1313#endif  /* _MERGESOLUTIONFROMFTOGX_H */
    14 
  • issm/trunk/src/c/modules/MeshPartitionx/MeshPartitionx.h

    r13395 r13975  
    88#include "../../include/include.h"
    99#include "../../EnumDefinitions/EnumDefinitions.h"
    10 
    1110
    1211/* local prototypes: */
     
    8988                /*Extrude epart2d to epart, using numlayers: */
    9089                epart=xNew<int>(numberofelements);
    91                
     90
    9291                count=0;
    9392                for(i=0;i<(numlayers-1);i++){
     
    10099                /*Extrude npart2d to npart, using numlayers: */
    101100                npart=xNew<int>(numberofnodes);
    102                
     101
    103102                count=0;
    104103                for(i=0;i<(numlayers);i++){
     
    109108                }
    110109        }
    111        
     110
    112111        /*Assign output pointer:*/
    113112        *pepart=epart;
  • issm/trunk/src/c/modules/MeshProfileIntersectionx/ElementSegment.cpp

    r13395 r13975  
    33
    44#include "./MeshProfileIntersectionx.h"
    5                
     5
    66void ElementSegment(DataSet* segments_dataset,int el,double* xnodes,double* ynodes,double* xsegment,double* ysegment){
    77
     
    99         * If they do, create a Segment object with the intersection, and add to segments_dataset dataset: */
    1010
    11         int i;
    12         double alpha;
    1311        double alpha1,alpha2;
    1412        double beta1,beta2;
    1513        double gamma1,gamma2;
    16        
     14
    1715        int    edge1,edge2,edge3;
    1816
     
    2119        double xfinal[2],yfinal[2];
    2220
    23        
    2421        /*edge 1: */
    2522        xel[0]=xnodes[0];  yel[0]=ynodes[0]; xel[1]=xnodes[1];  yel[1]=ynodes[1];
     
    4138        }
    4239        else if(    ((edge1==IntersectEnum) && (edge2==IntersectEnum)) || ((edge2==IntersectEnum) && (edge3==IntersectEnum)) || ((edge3==IntersectEnum) && (edge1==IntersectEnum))   ){
    43        
     40
    4441                /*segment interscts 2 opposite edges of our triangle, at 2 segment coordinates, pick up the lowest (coord1) and highest (coord2): */
    4542                if((edge1==IntersectEnum) && (edge2==IntersectEnum)) {coord1=min(alpha1,beta1); coord2=max(alpha1,beta1);}
     
    7774                        coord2=1.0;
    7875                }
    79                
     76
    8077                xfinal[0]=xsegment[0]+coord1*(xsegment[1]-xsegment[0]);
    8178                xfinal[1]=xsegment[0]+coord2*(xsegment[1]-xsegment[0]);
  • issm/trunk/src/c/modules/MeshProfileIntersectionx/ElementSegmentsIntersection.cpp

    r8303 r13975  
    33
    44#include "./MeshProfileIntersectionx.h"
    5                
     5
    66void ElementSegmentsIntersection(DataSet* segments_dataset,int el, double* xnodes,double* ynodes,double* xc,double* yc,int numnodes){
    77
  • issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.cpp

    r13395 r13975  
    77
    88        int i,j,k;
    9         int m,n;
    109
    1110        /*Contour:*/
     
    3231        /*Loop through all contours: */
    3332        for (i=0;i<numcontours;i++){
    34                
     33
    3534                /*retrieve contour info: */
    3635                contouri=*(contours+i);
     
    4140                /*determine segmentsi and numsegsi for this contour and the mesh intersection: */
    4241                MeshSegmentsIntersection(&segmentsi,&numsegsi,index,x,y,nel,nods,xc,yc,numnodes);
    43                
     42
    4443                /*save segmentsi: */
    4544                allsegments[i]=segmentsi;
  • issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshProfileIntersectionx.h

    r13395 r13975  
    22        MeshProfileIntersectionx.h
    33*/
    4 
    54
    65#ifndef _MESHPROFILEINTERSECTIONX_H
     
    1918
    2019#endif /* _MESHPROFILEINTERSECTIONX_H */
    21 
  • issm/trunk/src/c/modules/MeshProfileIntersectionx/MeshSegmentsIntersection.cpp

    r13395 r13975  
    1212        Segment<double>* segment=NULL;
    1313        int     numsegs;
    14        
     14
    1515        /*intermediary: */
    1616        DataSet* segments_dataset=NULL;
     
    3535        for(i=0;i<numsegs;i++){
    3636                Segment<double>* segment=(Segment<double>*)segments_dataset->GetObjectByOffset(i);
    37                
     37
    3838                /*x1,y1,x2,y2 then element_id: */
    3939                *(segments+5*i+0)=segment->x1;
  • issm/trunk/src/c/modules/MeshProfileIntersectionx/NodeInElement.cpp

    r8303 r13975  
    1919        y3=ynodes[2];
    2020
    21 
    2221        /*compute determinant: */
    2322        det=x1*y2-x1*y3-x3*y2-x2*y1+x2*y3+x3*y1;
    24        
     23
    2524        /*area coordinates: */
    2625        lambda1=((y2-y3)*(x-x3)+(x3-x2)*(y-y3))/det;
  • issm/trunk/src/c/modules/MeshProfileIntersectionx/SegmentIntersect.cpp

    r12330 r13975  
    1111        double alpha=-1;
    1212        double beta=-1;
    13        
     13
    1414        double xA,xB,xC,xD,yA,yB,yC,yD;
    1515        double O2A[2],O2B[2],O1C[2],O1D[2];
     
    2929        O1C[0]=xC -(xA/2+xB/2); O1C[1]=yC -(yA/2+yB/2);
    3030        O1D[0]=xD -(xA/2+xB/2); O1D[1]=yD -(yA/2+yB/2);
    31 
    3231
    3332        n1[0]=yA-yB; n1[1]=xB-xA;  //normal vector to segA
  • issm/trunk/src/c/modules/ModelProcessorx/Autodiff/CreateParametersAutodiff.cpp

    r13395 r13975  
    77#include "../../../io/io.h"
    88#include "../../../EnumDefinitions/EnumDefinitions.h"
    9 #include "../../../classes/objects/objects.h"
     9#include "../../../classes/classes.h"
    1010#include "../../../shared/shared.h"
    1111#include "../../../include/include.h"
     12#include "../../Solverx/Solverx.h"
    1213#include "../ModelProcessorx.h"
    1314
    1415void CreateParametersAutodiff(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type){
    15        
    16         int         i,j;
     16
     17        int         i;
    1718        Parameters *parameters       = NULL;
    1819        bool        autodiff_analysis;
    19         int*        dependents       = NULL;
    20         int         num_dependents;
    21         int*        independents       = NULL;
    22         int         num_independents;
    23         int         numberofvertices;
     20        int         num_dependent_objects;
     21        int         num_dep=0;
     22        int*        names=NULL;
     23        int*        types=NULL;
     24        int         dummy;
     25        char*       autodiff_driver=NULL;
     26        int*        indices=NULL;
     27        int         num_indices;
     28
    2429        IssmDouble* xp=NULL;
    25        
     30        IssmDouble* xp_backup=NULL;
     31        int         num_ind,local_num_ind;
     32        DataSet*    dependent_objects=NULL;
     33
    2634        /*Get parameters: */
    2735        parameters=*pparameters;
     
    2937        /*retrieve some parameters: */
    3038        iomodel->Constant(&autodiff_analysis,AutodiffIsautodiffEnum);
    31        
     39
    3240        if(autodiff_analysis){
    3341
    34                 iomodel->Constant(&num_independents,AutodiffNumIndependentsEnum);
    35                 iomodel->Constant(&num_dependents,AutodiffNumDependentsEnum);
    36                 iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
     42                #ifdef _HAVE_ADOLC_
    3743
    38                 /*recover dependents: */
    39                 parameters->AddObject(iomodel->CopyConstantObject(AutodiffNumDependentsEnum));
    40                 if(num_dependents){
    41                         iomodel->FetchData(&dependents,NULL,&num_dependents,AutodiffDependentsEnum);
    42                         parameters->AddObject(new IntVecParam(AutodiffDependentsEnum,dependents,num_dependents));
     44                /*Copy some parameters from IoModel to parameters dataset: */
     45                parameters->AddObject(iomodel->CopyConstantObject(AutodiffKeepEnum));
     46
     47                /*retrieve driver: {{{*/
     48                iomodel->Constant(&autodiff_driver,AutodiffDriverEnum);
     49                parameters->AddObject(iomodel->CopyConstantObject(AutodiffDriverEnum));
     50
     51                if(strcmp(autodiff_driver,"fos_forward")==0){
     52                        parameters->AddObject(iomodel->CopyConstantObject(AutodiffFosForwardIndexEnum));
    4353                }
     54                else if(strcmp(autodiff_driver,"fos_reverse")==0){
     55                        parameters->AddObject(iomodel->CopyConstantObject(AutodiffFosReverseIndexEnum));
     56                }
     57                else if(strcmp(autodiff_driver,"fov_forward")==0){
     58                        /*Retrieve list of indices: */
     59                        iomodel->FetchData(&indices,&num_indices,&dummy,AutodiffFovForwardIndicesEnum);
     60                        parameters->AddObject(new IntMatParam(AutodiffFovForwardIndicesEnum,indices,num_indices,1));
     61                        xDelete<int>(indices);
     62                }
     63                /*}}}*/
     64                /*Deal with dependents first: {{{*/
     65                iomodel->Constant(&num_dependent_objects,AutodiffNumDependentObjectsEnum);
     66                dependent_objects=new DataSet();
     67                num_dep=0;
    4468
    45                 /*recover independents: */
    46                 parameters->AddObject(iomodel->CopyConstantObject(AutodiffNumIndependentsEnum));
    47                 if(num_independents){
    48                         iomodel->FetchData(&independents,NULL,&num_independents,AutodiffIndependentsEnum);
    49                         parameters->AddObject(new IntVecParam(AutodiffIndependentsEnum,independents,num_independents));
     69                if(num_dependent_objects){
     70                        iomodel->FetchData(&names,&dummy,&dummy,AutodiffDependentObjectNamesEnum);
     71                        iomodel->FetchData(&types,&dummy,&dummy,AutodiffDependentObjectTypesEnum);
     72                        iomodel->FetchData(&indices,&dummy,&dummy,AutodiffDependentObjectIndicesEnum);
    5073
    51                         /*Build state vector, value at which we compute our gradients of dependent variables in adolc: the xp vector  */
    52                         xp=xNew<IssmDouble>(num_independents*numberofvertices);
    53                         for(i=0;i<num_independents;i++){
    54                                 IssmDouble* values=iomodel->data[independents[i]];
    55                                 for(j=0;j<numberofvertices;j++){
    56                                         xp[i*numberofvertices+j]=values[j];
    57                                 }
     74                        for(i=0;i<num_dependent_objects;i++){
     75                                DependentObject* dep=new DependentObject(names[i],types[i],indices[i]);
     76                                dependent_objects->AddObject(dep);
     77                                num_dep+=dep->NumDependents();
    5878                        }
    59                         parameters->AddObject(new DoubleVecParam(AutodiffXpEnum,xp,num_independents*numberofvertices));
     79
     80                        /*Free ressources:*/
     81                        xDelete<int>(names);
     82                        xDelete<int>(types);
    6083                }
     84                parameters->AddObject(new DataSetParam(AutodiffDependentObjectsEnum,dependent_objects));
     85                parameters->AddObject(new IntParam(AutodiffNumDependentsEnum,num_dep));
    6186
    62                 /*Assign output pointer: */
    63                 *pparameters=parameters;
     87                delete dependent_objects;
     88                /*}}}*/
     89                /*Deal with independents: {{{*/
     90
     91                /*Independents have already been recovered in iomodel->DeclareIndependents. Just do some more processing.
     92                 *In particular, figure out num_independents, and create the state vector xp, or size num_independents x 1 :*/
     93                num_ind=0;
     94                for(i=0;i<iomodel->independent_objects->Size();i++){
     95                        IndependentObject* ind=(IndependentObject*)iomodel->independent_objects->GetObjectByOffset(i);
     96                        num_ind+=ind->NumIndependents();
     97                }
     98                if(num_ind){
     99                        xp=xNew<IssmDouble>(num_ind);
     100                        xp_backup=xp;
     101                        for(i=0;i<iomodel->independent_objects->Size();i++){
     102                                IndependentObject* ind=(IndependentObject*)iomodel->independent_objects->GetObjectByOffset(i);
     103                                ind->FillIndependents(iomodel->data,xp);
     104                                local_num_ind=ind->NumIndependents(); xp=xp+local_num_ind;
     105                        }
     106                        xp=xp_backup; parameters->AddObject(new DoubleVecParam(AutodiffXpEnum,xp,num_ind));
     107                }
     108                parameters->AddObject(new IntParam(AutodiffNumIndependentsEnum,num_ind));
     109
     110                /*Don't forget to copy  iomodel->independent_objects to parameters: */
     111                parameters->AddObject(new DataSetParam(AutodiffIndependentObjectsEnum,iomodel->independent_objects));
     112                /*}}}*/
     113
     114                #endif
    64115        }
     116
     117        #ifdef _HAVE_ADOLC_
     118                /*initialize a placeholder to store solver pointers: {{{*/
     119                GenericParam<Adolc_edf> *theAdolcEDF_p=new GenericParam<Adolc_edf>(AdolcParamEnum);
     120                theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p=reg_ext_fct(EDF_for_solverx);
     121                // to save some space:
     122                // we know we won't use adolc inside of  the solver:
     123                theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p->nestedAdolc=false;
     124                // the solution vector is just allocated and doesn't have a meaningfull prior value
     125                theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p->dp_y_priorRequired=false;
     126                // the solver wrapper makes sure the matrix and the right hand side don't change
     127                theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p->dp_x_changes=false;
     128                parameters->AddObject(theAdolcEDF_p);
     129                /*}}}*/
     130        #endif
     131
     132        /*Assign output pointer: */
     133        *pparameters=parameters;
     134
    65135}
  • issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateConstraintsBalancethickness.cpp

    r13395 r13975  
    1010void    CreateConstraintsBalancethickness(Constraints** pconstraints, IoModel* iomodel){
    1111
     12        /*Fetch parameters: */
    1213        int    stabilization;   
    13        
    14         /*Fetch parameters: */
    1514        iomodel->Constant(&stabilization,BalancethicknessStabilizationEnum);
    1615
    17         /*Output*/
    18         Constraints* constraints = NULL;
    19 
    2016        /*Recover pointer: */
    21         constraints=*pconstraints;
     17        Constraints* constraints=*pconstraints;
    2218
    2319        /*Create constraints if they do not exist yet*/
  • issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateLoadsBalancethickness.cpp

    r13395 r13975  
    1414
    1515        /*Intermediary*/
    16         int i;
    1716        int element;
    1817        int stabilization;
     
    2322        iomodel->Constant(&numberofedges,MeshNumberofedgesEnum);
    2423
    25         /*Output*/
    26         Loads*    loads    = NULL;
    27 
    2824        /*Recover pointer: */
    29         loads=*ploads;
     25        Loads* loads=*ploads;
    3026
    3127        /*Create loads if they do not exist yet*/
    3228        if(!loads) loads = new Loads();
    33        
     29
    3430        /*Loads only in DG*/
    3531        if (stabilization==3){
     
    3935
    4036                /*First load data:*/
    41                 for (i=0;i<numberofedges;i++){
     37                for (int i=0;i<numberofedges;i++){
    4238
    4339                        /*Get left and right elements*/
  • issm/trunk/src/c/modules/ModelProcessorx/Balancethickness/CreateNodesBalancethickness.cpp

    r13395 r13975  
    2626        int    stabilization;
    2727
    28         /*DataSets: */
    29         Nodes*    nodes = NULL;
    30 
    3128        /*Fetch parameters: */
    3229        iomodel->Constant(&dim,MeshDimensionEnum);
     
    3633
    3734        /*Recover pointer: */
    38         nodes=*pnodes;
     35        Nodes* nodes=*pnodes;
    3936
    4037        /*Create nodes if they do not exist yet*/
  • issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateConstraintsBedSlope.cpp

    r13395 r13975  
    1313void    CreateConstraintsBedSlope(Constraints** pconstraints, IoModel* iomodel){
    1414
    15         /*Output*/
    16         Constraints* constraints = NULL;
    17        
    1815        /*Recover pointer: */
    19         constraints=*pconstraints;
     16        Constraints* constraints=*pconstraints;
    2017
    2118        /*Create constraints if they do not exist yet*/
  • issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateLoadsBedSlope.cpp

    r13395 r13975  
    1313void    CreateLoadsBedSlope(Loads** ploads, IoModel* iomodel){
    1414
    15         /*DataSet*/
    16         Loads*    loads    = NULL;
    17 
    1815        /*Recover pointer: */
    19         loads=*ploads;
     16        Loads* loads=*ploads;
    2017
    2118        /*Create loads if they do not exist yet*/
  • issm/trunk/src/c/modules/ModelProcessorx/BedSlope/CreateNodesBedSlope.cpp

    r13395 r13975  
    1818        int i;
    1919        bool continuous_galerkin=true;
    20         int    numberofvertices;
    21 
    22         /*DataSets: */
    23         Nodes*    nodes = NULL;
    2420
    2521        /*Fetch parameters: */
     22        int    numberofvertices;
    2623        iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
    2724
    2825        /*Recover pointer: */
    29         nodes=*pnodes;
     26        Nodes* nodes=*pnodes;
    3027
    3128        /*Create nodes if they do not exist yet*/
    3229        if(!nodes) nodes = new Nodes();
    33        
     30
    3431        /*Continuous Galerkin partition of nodes: */
    3532        NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
    36        
     33
    3734        /*First fetch data: */
    3835        iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
     
    4037        for (i=0;i<numberofvertices;i++){
    4138                if(iomodel->my_vertices[i]){
    42                        
     39
    4340                        /*Add node to nodes dataset: */
    4441                        nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,BedSlopeAnalysisEnum));
     
    4946        /*Clean fetched data: */
    5047        iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
    51        
     48
    5249        /*Assign output pointer: */
    5350        *pnodes=nodes;
  • issm/trunk/src/c/modules/ModelProcessorx/BedSlope/UpdateElementsBedSlope.cpp

    r13395 r13975  
    4242                iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
    4343        }
    44        
     44
    4545        /*Free data: */
    4646        iomodel->DeleteData(1,MeshElementsEnum);
  • issm/trunk/src/c/modules/ModelProcessorx/Control/CreateParametersControl.cpp

    r13395 r13975  
    1313
    1414void CreateParametersControl(Parameters** pparameters,IoModel* iomodel,int solution_type,int analysis_type){
    15        
    16         int         i;
     15
    1716        Parameters *parameters       = NULL;
    1817        bool        control_analysis;
     
    2120        int         num_cm_responses;
    2221        int        *control_type     = NULL;
    23         IssmDouble     *cm_responses     = NULL;
    24         IssmDouble     *cm_jump          = NULL;
    25         IssmDouble     *optscal          = NULL;
    26         IssmDouble     *maxiter          = NULL;
     22        IssmDouble *cm_responses     = NULL;
     23        IssmDouble *cm_jump          = NULL;
     24        IssmDouble *optscal          = NULL;
     25        IssmDouble *maxiter          = NULL;
    2726
    2827        /*Get parameters: */
  • issm/trunk/src/c/modules/ModelProcessorx/Control/UpdateElementsAndMaterialsControl.cpp

    r13395 r13975  
    2525        bool   control_analysis;
    2626
    27        
    2827        /*Fetch parameters: */
    2928        iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
     
    6564                }
    6665        }
    67        
     66
    6867        /*Free data: */
    6968        iomodel->DeleteData(1+4+6,MeshElementsEnum,InversionControlParametersEnum,InversionCostFunctionsCoefficientsEnum,InversionMinParametersEnum,InversionMaxParametersEnum,BalancethicknessThickeningRateEnum,VxEnum,VyEnum,FrictionCoefficientEnum,MaterialsRheologyBEnum,MaterialsRheologyZEnum);
  • issm/trunk/src/c/modules/ModelProcessorx/CreateDataSets.cpp

    r13395 r13975  
    1515#include "./ModelProcessorx.h"
    1616
    17 
    1817void CreateDataSets(Elements** pelements,Nodes** pnodes, Vertices** pvertices, Materials** pmaterials, Constraints** pconstraints, Loads** ploads,Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,const int analysis_type,const int nummodels,int analysis_counter){
    1918
     
    2221        Materials  *materials  = NULL;
    2322        Parameters *parameters = NULL;
    24                        
     23
    2524        /*Create elements, vertices and materials, independent of analysis_type: */
    2625        CreateElementsVerticesAndMaterials(pelements, pvertices, pmaterials, iomodel,nummodels);
     
    4039                        UpdateElementsDiagnosticHoriz(elements,iomodel,analysis_counter,analysis_type);
    4140                        break;
    42                
     41
    4342                case DiagnosticVertAnalysisEnum:
    4443                        CreateNodesDiagnosticVert(pnodes, iomodel);
     
    4746                        UpdateElementsDiagnosticVert(elements,iomodel,analysis_counter,analysis_type);
    4847                        break;
    49        
     48
    5049                case DiagnosticHutterAnalysisEnum:
    5150                        CreateNodesDiagnosticHutter(pnodes, iomodel);
     
    5554                        break;
    5655                #endif
    57                
     56
    5857                #ifdef _HAVE_HYDROLOGY_
    5958                case HydrologyAnalysisEnum:
     
    7271                        UpdateElementsThermal(elements,iomodel,analysis_counter,analysis_type);
    7372                        break;
    74        
     73
    7574                case EnthalpyAnalysisEnum:
    7675                        CreateNodesEnthalpy(pnodes, iomodel);
     
    7978                        UpdateElementsEnthalpy(elements,iomodel,analysis_counter,analysis_type);
    8079                        break;
    81                
     80
    8281                case MeltingAnalysisEnum:
    8382                        CreateNodesMelting(pnodes, iomodel);
     
    122121                #endif
    123122
    124 
    125123                default:
    126124                        _error_("analysis_type: " << EnumToStringx(analysis_type) << " not supported yet!");
  • issm/trunk/src/c/modules/ModelProcessorx/CreateElementsVerticesAndMaterials.cpp

    r13395 r13975  
    1616
    1717        /*Intermediary*/
    18         int i,j,k,n;
     18        int i;
    1919        int dim,materials_type;
    2020        int numberofelements;
     
    4141        vertices  = new Vertices();
    4242        materials = new Materials();
    43        
     43
    4444        /*First, partition elements and vertices. Nodes will partitioned on a per analysis_type basis. If partitining already done, ignore: */
    4545        ElementsAndVerticesPartitioning(&iomodel->my_elements,&iomodel->my_vertices,iomodel);
    46        
     46
    4747        iomodel->FetchData(2,MeshElementsEnum,MeshElementconnectivityEnum);
    4848        #ifdef _HAVE_3D_
     
    5050        #endif
    5151        if(control_analysis)iomodel->FetchData(3,InversionControlParametersEnum,InversionMinParametersEnum,InversionMaxParametersEnum);
    52        
     52
    5353        /*Create elements*/
    5454        for (i=0;i<numberofelements;i++){
     
    6262                }
    6363        }
    64        
     64
    6565        /*Create materials*/
    6666        switch(materials_type){
     
    8484        /*Add new constant material property to materials, at the end: */
    8585        materials->AddObject(new Matpar(numberofelements+1,iomodel));//put it at the end of the materials
    86        
     86
    8787        /*Create vertices: */
    8888
     
    9090        iomodel->FetchData(6,MeshElementsEnum,MeshXEnum,MeshYEnum,MeshZEnum,BedEnum,ThicknessEnum);
    9191        CreateNumberNodeToElementConnectivity(iomodel);
    92        
     92
    9393        for (i=0;i<numberofvertices;i++){
    9494
    9595                /*vertices and nodes (same number, as we are running continuous galerkin formulation): */
    9696                if(iomodel->my_vertices[i]){
    97                        
     97
    9898                        /*Add vertex to vertices dataset: */
    9999                        vertices->AddObject(new Vertex(i+1,i,i,iomodel));
  • issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp

    r13395 r13975  
    88#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
    99#endif
    10 
    1110
    1211#include "../../Container/Container.h"
     
    2019
    2120void CreateParameters(Parameters** pparameters,IoModel* iomodel,char* rootpath,const int solution_type,int analysis_type,int analysis_counter){
    22        
    23         int         i;
     21
     22        int         i,j,m,k;
    2423        int         numoutputs;
    2524        Parameters *parameters       = NULL;
     
    2726        bool        isdelta18o;
    2827
     28        /*parameters for mass flux: {{{*/
     29        int      mass_flux_num_profiles=0;
     30        bool     qmu_mass_flux_present=false;
     31        bool     autodiff_mass_flux_present=false;
     32        bool     mass_flux_present=false;
     33        IssmDouble** array=NULL;
     34        int*     mdims_array=NULL;
     35        int*     ndims_array=NULL;
     36        IssmDouble*  temp_matrix=NULL;
     37        int      temp_m,temp_n;
     38        IssmDouble*  matrix=NULL;
     39        int      count;
     40        /*}}}*/
     41
    2942        if(*pparameters)return; //do not create parameters twice!
    3043
    3144        /*Initialize dataset: */
    3245        parameters = new Parameters();
    33                
     46
    3447        /*Copy some constants from iomodel */
    3548        parameters->AddObject(iomodel->CopyConstantObject(MeshDimensionEnum));
     
    127140        if(numoutputs)parameters->AddObject(new IntVecParam(DiagnosticRequestedOutputsEnum,requestedoutputs,numoutputs));
    128141        iomodel->DeleteData(requestedoutputs,DiagnosticRequestedOutputsEnum);
     142
    129143        iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,TransientRequestedOutputsEnum);
    130144        parameters->AddObject(new IntParam(TransientNumRequestedOutputsEnum,numoutputs));
    131145        if(numoutputs)parameters->AddObject(new IntVecParam(TransientRequestedOutputsEnum,requestedoutputs,numoutputs));
    132146        iomodel->DeleteData(requestedoutputs,TransientRequestedOutputsEnum);
     147
    133148        iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,SteadystateRequestedOutputsEnum);
    134149        parameters->AddObject(new IntParam(SteadystateNumRequestedOutputsEnum,numoutputs));
    135150        if(numoutputs)parameters->AddObject(new IntVecParam(SteadystateRequestedOutputsEnum,requestedoutputs,numoutputs));
    136151        iomodel->DeleteData(requestedoutputs,SteadystateRequestedOutputsEnum);
    137        
     152
     153        iomodel->FetchData(&requestedoutputs,&numoutputs,NULL,PrognosticRequestedOutputsEnum);
     154        parameters->AddObject(new IntParam(PrognosticNumRequestedOutputsEnum,numoutputs));
     155        if(numoutputs)parameters->AddObject(new IntVecParam(PrognosticRequestedOutputsEnum,requestedoutputs,numoutputs));
     156        iomodel->DeleteData(requestedoutputs,PrognosticRequestedOutputsEnum);
     157
     158        /*Deal with mass flux segments: {{{*/
     159        iomodel->FetchData(&qmu_mass_flux_present,QmuMassFluxSegmentsPresentEnum);
     160        iomodel->FetchData(&autodiff_mass_flux_present,AutodiffMassFluxSegmentsPresentEnum);
     161
     162        if(qmu_mass_flux_present || autodiff_mass_flux_present)mass_flux_present=true;
     163        else mass_flux_present=false;
     164        parameters->AddObject(new BoolParam(MassFluxSegmentsPresentEnum,mass_flux_present));
     165
     166        if(mass_flux_present){
     167
     168                /*Fetch the mass flux segments necessary to compute the mass fluxes.  Build a DoubleMatArrayParam object out of them: */
     169                iomodel->FetchData(&array,&mdims_array,&ndims_array,&mass_flux_num_profiles,MassFluxSegmentsEnum);
     170                if(mass_flux_num_profiles==0)_error_("mass_flux_num_profiles is 0, when MassFlux computations were requested!");
     171
     172                /*Go through segments, and extract those that belong to this cpu: */
     173                for(i=0;i<mass_flux_num_profiles;i++){
     174                        temp_matrix=array[i];
     175                        temp_m=mdims_array[i];
     176                        temp_n=ndims_array[i];
     177
     178                        m=0;
     179                        for(j=0;j<temp_m;j++){
     180                                if (  iomodel->my_elements[reCast<int>(*(temp_matrix+5*j+4))-1] )m++;
     181                        }
     182                        if(m){
     183                                matrix=xNewZeroInit<IssmDouble>(5*m);
     184                                count=0;
     185                                for(j=0;j<temp_m;j++){
     186                                        if (iomodel->my_elements[reCast<int>(*(temp_matrix+5*j+4))-1]){
     187                                                for(k=0;k<5;k++)*(matrix+5*count+k)=*(temp_matrix+5*j+k);
     188                                                count++;
     189                                        }
     190                                }
     191                        }
     192                        else{
     193                                matrix=NULL;
     194                        }
     195
     196                        /*Assign: */
     197                        array[i]=matrix;
     198                        mdims_array[i]=m;
     199                        ndims_array[i]=5;
     200
     201                        /*Free temporary matrix: */
     202                        xDelete<IssmDouble>(temp_matrix);
     203                }
     204
     205                /*Ok, we have an array of segments, different on every cpu. Create a DoubleMatArrayParam object with it: */
     206                parameters->AddObject(new DoubleMatArrayParam(MassFluxSegmentsEnum,array,mass_flux_num_profiles,mdims_array,ndims_array));
     207
     208                /*Free data: */
     209                for(i=0;i<mass_flux_num_profiles;i++){
     210                        IssmDouble* matrix=array[i];
     211                        xDelete<IssmDouble>(matrix);
     212                }
     213                xDelete<int>(mdims_array);
     214                xDelete<int>(ndims_array);
     215                xDelete<IssmDouble*>(array);
     216        }
     217        /*}}}*/
     218
    138219        /*Before returning, create parameters in case we are running Qmu or control types runs: */
    139220        #ifdef _HAVE_CONTROL_
  • issm/trunk/src/c/modules/ModelProcessorx/Dakota/CreateParametersDakota.cpp

    r13395 r13975  
    1616
    1717        /*variable declarations: {{{*/
    18         int i,j,k;
    19        
     18        int i;
    2019        Parameters* parameters = NULL;
    21         int      second_count;
    22        
     20
    2321        int*     part=NULL;
    2422        double*  dpart=NULL;
     
    3533        char* qmuerrname=NULL;
    3634        char* qmuoutname=NULL;
    37        
     35
    3836        //descriptors:
    3937        char tag[50];
    40        
    41         /*parameters for mass flux: */
    42         bool     qmu_mass_flux_present=false;
    43         int qmu_mass_flux_num_profiles=0;
    44         double** array=NULL;
    45         int*     mdims_array=NULL;
    46         int*     ndims_array=NULL;
    47        
    48         double*  matrix=NULL;
    49         double*  temp_matrix=NULL;
    50         int      M;
    51         int      temp_m,temp_n;
    52         int      m,n;
    53         int      count;
     38
    5439        bool     dakota_analysis=false;
    5540        char*    name=NULL;
     
    6045
    6146        /*}}}*/
    62        
     47
    6348        /*recover parameters : */
    6449        parameters=*pparameters;
     
    10287                /*Deal with partitioning: {{{*/
    10388                /*partition vertices in iomodel->qmu_npart parts, unless a partition is already present: */
    104                
     89
    10590                parameters->AddObject(iomodel->CopyConstantObject(QmuNumberofpartitionsEnum));
    10691                iomodel->FetchData(&dpart,NULL,NULL,QmuPartitionEnum);
     
    117102                /*}}}*/
    118103                /*Deal with data needed because of qmu variables: {{{*/
    119                
     104
    120105                for(i=0;i<numvariabledescriptors;i++){
    121106
     
    123108                                /*Ok, we are dealing with a variable that is distributed over nodes. Recover the name of the variable (ex: scaled_Thickness): */
    124109                                sscanf(variabledescriptors[i],"scaled_%s",tag);
    125                                
     110
    126111                                /*Recover data: */
    127112                                iomodel->FetchData(&dakota_parameter,&nrows,&ncols,StringToEnumx(tag));
     
    134119                                        parameters->AddObject(new DoubleTransientMatParam(StringToEnumx(tag),dakota_parameter,nrows,ncols));
    135120                                }
    136                                
     121
    137122                                /*Free ressources:*/
    138123                                xDelete<double>(dakota_parameter);
    139124                        }
    140                 }
    141                 /*}}}*/
    142                 /*Deal with data needed to compute qmu responses: {{{*/
    143                 for(i=0;i<numresponsedescriptors;i++){
    144                        
    145                         if(strncmp(responsedescriptors[i],"indexed_MassFlux",16)==0){
    146                                 qmu_mass_flux_present=true;
    147                         }
    148                 }
    149                
    150                
    151                 if(qmu_mass_flux_present){
    152                        
    153                         /*Fetch the mass flux segments necessary to compute the mass fluxes.  Build a DoubleMatArrayParam object out of them: */
    154                         iomodel->FetchData(&array,&mdims_array,&ndims_array,&qmu_mass_flux_num_profiles,QmuMassFluxSegmentsEnum);
    155                         if(qmu_mass_flux_num_profiles==0)_error_("qmu_mass_flux_num_profiles is 0, when MassFlux computations were requested!");
    156 
    157                         /*Go through segments, and extract those that belong to this cpu: */
    158                         for(i=0;i<qmu_mass_flux_num_profiles;i++){
    159                                 temp_matrix=array[i];
    160                                 temp_m=mdims_array[i];
    161                                 temp_n=ndims_array[i];
    162 
    163                                 m=0;
    164                                 for(j=0;j<temp_m;j++){
    165                                         if (  iomodel->my_elements[(int)(*(temp_matrix+5*j+4))-1])m++;
    166                                 }
    167                                 if(m){
    168                                         matrix=xNewZeroInit<double>(5*m);
    169                                         count=0;
    170                                         for(j=0;j<temp_m;j++){
    171                                                 if (iomodel->my_elements[(int)*(temp_matrix+5*j+4)-1]){
    172                                                         for(k=0;k<5;k++)*(matrix+5*count+k)=*(temp_matrix+5*j+k);
    173                                                         count++;
    174                                                 }
    175                                         }
    176                                 }
    177                                 else{
    178                                         matrix=NULL;
    179                                 }
    180 
    181                                 /*Assign: */
    182                                 array[i]=matrix;
    183                                 mdims_array[i]=m;
    184                                 ndims_array[i]=5;
    185 
    186                                 /*Free temporary matrix: */
    187                                 xDelete<double>(temp_matrix);
    188                         }
    189 
    190                         /*Ok, we have an array of segments, different on every cpu. Create a DoubleMatArrayParam object with it: */
    191                         parameters->AddObject(new DoubleMatArrayParam(QmuMassFluxSegmentsEnum,array,qmu_mass_flux_num_profiles,mdims_array,ndims_array));
    192 
    193                         /*Free data: */
    194                         for(i=0;i<qmu_mass_flux_num_profiles;i++){
    195                                 double* matrix=array[i];
    196                                 xDelete<double>(matrix);
    197                         }
    198                         xDelete<int>(mdims_array);
    199                         xDelete<int>(ndims_array);
    200                         xDelete<double*>(array);
    201125                }
    202126                /*}}}*/
  • issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateConstraintsDiagnosticHoriz.cpp

    r13395 r13975  
    4444        Constraints *constraints      = NULL;
    4545        SpcStatic   *spcstatic        = NULL;
    46         int          node1,node2;
    4746        int          dim;
    4847        int          numberofvertices;
     
    6463        /*Create constraints if they do not exist yet*/
    6564        if(!constraints) constraints = new Constraints();
    66        
     65
    6766        /*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
    6867        if(!ismacayealpattyn & !isstokes & !isl1l2){
     
    7069                return;
    7170        }
    72        
     71
    7372        /*Constraints: fetch data: */
    7473        iomodel->FetchData(&spcvx,&Mx,&Nx,DiagnosticSpcvxEnum);
     
    324323                }
    325324        }
    326          
     325
    327326        /*Free data: */
    328327        iomodel->DeleteData(spcvx,DiagnosticSpcvxEnum);
  • issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateLoadsDiagnosticHoriz.cpp

    r13395 r13975  
    1414
    1515        /*DataSets*/
    16         Loads     *loads     = NULL;
    1716        Icefront  *icefront  = NULL;
    18         Riftfront *riftfront = NULL;
    1917        Pengrid   *pengrid   = NULL;
    2018
     
    4846
    4947        /*Recover pointer: */
    50         loads=*ploads;
     48        Loads* loads=*ploads;
    5149
    5250        /*Create loads if they do not exist yet*/
     
    5856                return;
    5957        }
    60        
     58
    6159        /*Create pressure loads as boundary conditions. Pay attention to the partitioning if we are running in parallel (the nodes
    6260         * referenced by a certain load must belong to the cluster node): */
     
    7068        /*First load data:*/
    7169        for (i=0;i<numberofpressureloads;i++){
    72                
     70
    7371                /*Retrieve element to which this icefront belongs: */
    7472                if (dim==2) segment_width=4;
     
    7876                /*Now, if this element is not in the partition, pass: */
    7977                if(!iomodel->my_elements[element]) continue;
    80                
     78
    8179                /*Do not create ice front if Hutter or Stokes elements*/
    8280                if (reCast<int,IssmDouble>(*(elements_type+element))==HutterApproximationEnum) continue;
     
    132130        iomodel->DeleteData(pressureload,DiagnosticIcefrontEnum);
    133131
    134 
    135132        /*Create Penpair for penalties: */
    136133        iomodel->FetchData(&penalties,&numpenalties,NULL,DiagnosticVertexPairingEnum);
    137        
     134
    138135        for(i=0;i<numpenalties;i++){
    139136
     
    167164                }
    168165                iomodel->DeleteData(5,RiftsRiftstructEnum,ThicknessEnum,BedEnum,SurfaceEnum,MaskVertexonfloatingiceEnum);
    169                 xDelete<Riftfront>(riftfront);
     166                xDelete<IssmDouble>(riftinfo);
    170167        }
    171168
  • issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/CreateNodesDiagnosticHoriz.cpp

    r13395 r13975  
    2121        bool   isstokes,isl1l2,ismacayealpattyn;
    2222
    23         /*DataSets: */
    24         Nodes*    nodes = NULL;
    25 
    2623        /*Fetch parameters: */
    2724        iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
     
    3128
    3229        /*Recover pointer: */
    33         nodes=*pnodes;
     30        Nodes* nodes=*pnodes;
    3431
    3532        /*First create nodes*/
    3633        if(!nodes) nodes = new Nodes();
    37        
     34
    3835        /*Now, is the flag macayaealpattyn on? otherwise, do nothing: */
    3936        if(!ismacayealpattyn & !isstokes & !isl1l2){
     
    4845        iomodel->FetchData(9,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,FlowequationBordermacayealEnum,FlowequationBorderstokesEnum,
    4946                                MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,MaskVertexonwaterEnum,FlowequationVertexEquationEnum,DiagnosticReferentialEnum);
    50        
     47
    5148        for (i=0;i<numberofvertices;i++){
    5249
    5350                if(iomodel->my_vertices[i]){
    54                        
     51
    5552                        /*Add node to nodes dataset: */
    5653                        nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,DiagnosticHorizAnalysisEnum));
  • issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHoriz/UpdateElementsDiagnosticHoriz.cpp

    r13395 r13975  
    8585        elements->InputDuplicate(VxEnum,InversionVxObsEnum);
    8686        if(dakota_analysis)elements->InputDuplicate(VxEnum,QmuVxEnum);
    87        
     87
    8888        elements->InputDuplicate(VyEnum,VyPicardEnum);
    8989        elements->InputDuplicate(VyEnum,InversionVyObsEnum);
    9090        if(dakota_analysis)elements->InputDuplicate(VyEnum,QmuVyEnum);
    91        
     91
    9292        if(dim==3){
    9393                elements->InputDuplicate(VzEnum,VzPicardEnum);
     
    9595                if(dakota_analysis)elements->InputDuplicate(VzEnum,QmuVzEnum);
    9696        }
    97        
     97
    9898        /*Free data: */
    9999        iomodel->DeleteData(2,MeshElementsEnum,FlowequationElementEquationEnum);
  • issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateConstraintsDiagnosticHutter.cpp

    r13395 r13975  
    7575        /*Free data: */
    7676        iomodel->DeleteData(3,DiagnosticSpcvxEnum,DiagnosticSpcvyEnum,FlowequationVertexEquationEnum);
    77        
     77
    7878        /*Assign output pointer: */
    7979        *pconstraints=constraints;
  • issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateLoadsDiagnosticHutter.cpp

    r13395 r13975  
    1313void    CreateLoadsDiagnosticHutter(Loads** ploads, IoModel* iomodel){
    1414
    15         /*DataSet*/
    16         Loads* loads=NULL;
    17 
    1815        /*Recover pointer: */
    19         loads=*ploads;
     16        Loads* loads=*ploads;
    2017
    2118        /*Create loads if they do not exist yet*/
    2219        if(!loads) loads = new Loads();
    23        
     20
    2421        /*Assign output pointer: */
    2522        *ploads=loads;
  • issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/CreateNodesDiagnosticHutter.cpp

    r13395 r13975  
    2121        bool   ishutter;
    2222
    23         /*DataSets: */
    24         Nodes*    nodes = NULL;
    25 
    2623        /*Fetch parameters: */
    2724        iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
     
    2926
    3027        /*Recover pointer: */
    31         nodes=*pnodes;
     28        Nodes* nodes=*pnodes;
    3229
    3330        /*Create nodes if they do not exist yet*/
  • issm/trunk/src/c/modules/ModelProcessorx/DiagnosticHutter/UpdateElementsDiagnosticHutter.cpp

    r13395 r13975  
    1919        bool   ishutter;
    2020
    21        
    2221        /*Fetch data needed: */
    2322        iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
     
    3837                }
    3938        }
    40        
     39
    4140        iomodel->FetchDataToInput(elements,ThicknessEnum);
    4241        iomodel->FetchDataToInput(elements,GeometryHydrostaticRatioEnum);
    43        
     42
    4443        /*Free data: */
    4544        iomodel->DeleteData(2,MeshElementsEnum,FlowequationElementEquationEnum);
  • issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateConstraintsDiagnosticVert.cpp

    r13395 r13975  
    2020        int    numberofvertices;
    2121
    22         /*Output*/
    23         Constraints* constraints = NULL;
    24 
    2522        /*Fetch parameters: */
    2623        iomodel->Constant(&dim,MeshDimensionEnum);
     
    2926
    3027        /*Recover pointer: */
    31         constraints=*pconstraints;
     28        Constraints* constraints=*pconstraints;
    3229
    3330        /*Create constraints if they do not exist yet*/
  • issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateLoadsDiagnosticVert.cpp

    r13395 r13975  
    1313void    CreateLoadsDiagnosticVert(Loads** ploads, IoModel* iomodel){
    1414
    15         /*DataSet*/
    16         Loads* loads=NULL;
    17 
    1815        /*Recover pointer: */
    19         loads=*ploads;
     16        Loads* loads=*ploads;
    2017
    2118        /*Create loads if they do not exist yet*/
  • issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/CreateNodesDiagnosticVert.cpp

    r13395 r13975  
    2121        int    numberofvertices;
    2222
    23         /*DataSets: */
    24         Nodes*    nodes = NULL;
    25 
    2623        /*Fetch parameters: */
    2724        iomodel->Constant(&dim,MeshDimensionEnum);
     
    2926
    3027        /*Recover pointer: */
    31         nodes=*pnodes;
     28        Nodes* nodes=*pnodes;
    3229
    3330        /*Create nodes if they do not exist yet*/
     
    4239        /*Continuous Galerkin partition of nodes: */
    4340        NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
    44        
     41
    4542        /*First fetch data: */
    4643        iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
     
    5754        /*Clean fetched data: */
    5855        iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
    59        
     56
    6057        /*Assign output pointer: */
    6158        *pnodes=nodes;
  • issm/trunk/src/c/modules/ModelProcessorx/DiagnosticVert/UpdateElementsDiagnosticVert.cpp

    r13395 r13975  
    5454        /*Free data: */
    5555        iomodel->DeleteData(1,MeshElementsEnum);
    56        
     56
    5757}
  • issm/trunk/src/c/modules/ModelProcessorx/DistributeNumDofs.cpp

    r13395 r13975  
    66#include "../../include/include.h"
    77#include "../../EnumDefinitions/EnumDefinitions.h"
    8        
     8
    99void DistributeNumDofs(DofIndexing* index,int analysis_type,IssmDouble* vertices_type){
    1010
     
    1313
    1414        int numdofs=2; //default numdofs
    15         int i;
    1615        int* doftype=NULL;
    1716
  • issm/trunk/src/c/modules/ModelProcessorx/ElementsAndVerticesPartitioning.cpp

    r13395 r13975  
    2222        int i;
    2323
    24         extern int my_rank;
    25         extern int num_procs;
     24        int my_rank;
     25        int num_procs;
    2626        int    numberofelements;
    2727        int    numberofvertices;
     
    4646        IssmDouble* riftinfo=NULL;
    4747        IssmDouble* vertex_pairing=NULL;
     48
     49        /*Get my_rank:*/
     50        my_rank=IssmComm::GetRank();
     51        num_procs=IssmComm::GetSize();
    4852
    4953        /*Fetch parameters: */
     
    102106
    103107                        my_elements[i]=true;
    104                        
     108
    105109                        /*Now that we are here, we can also start building the list of vertices belonging to this cpu partition: we use
    106110                         *the  element index to do this. For each element n, we know index[n][0:2] holds the indices (matlab indexing)
     
    110114                        my_vertices[reCast<int>(*(elements+elements_width*i+1))-1]=1;
    111115                        my_vertices[reCast<int>(*(elements+elements_width*i+2))-1]=1;
    112                        
     116
    113117                        if(elements_width==6){
    114118                                my_vertices[reCast<int>(*(elements+elements_width*i+3))-1]=1;
  • issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateConstraintsEnthalpy.cpp

    r13395 r13975  
    2323        IssmDouble heatcapacity;
    2424        IssmDouble referencetemperature;
    25        
     25
    2626        /*Output*/
    2727        IssmDouble *spcvector  = NULL;
    2828        IssmDouble* times=NULL;
    2929        IssmDouble* values=NULL;
    30         Constraints* constraints = NULL;
    3130
    3231        /*Fetch parameters: */
     
    3736
    3837        /*Recover pointer: */
    39         constraints=*pconstraints;
     38        Constraints* constraints=*pconstraints;
    4039
    4140        /*Create constraints if they do not exist yet*/
     
    8584                /*Create constraints from x,y,z: */
    8685                for (i=0;i<numberofvertices;i++){
    87                        
     86
    8887                        /*keep only this partition's nodes:*/
    8988                        if((iomodel->my_vertices[i])){
  • issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateLoadsEnthalpy.cpp

    r13395 r13975  
    1313void    CreateLoadsEnthalpy(Loads** ploads, IoModel* iomodel){
    1414
    15         /*DataSet*/
    16         Loads* loads=NULL;
    17 
    1815        /*Recover pointer: */
    19         loads=*ploads;
     16        Loads* loads=*ploads;
    2017
    2118        /*Create loads if they do not exist yet*/
    2219        if(!loads) loads = new Loads();
    2320
    24 
    2521        /*Assign output pointer: */
    2622        *ploads=loads;
  • issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/CreateNodesEnthalpy.cpp

    r13395 r13975  
    2020        int    numberofvertices;
    2121
    22         /*DataSets: */
    23         Nodes*    nodes = NULL;
    24 
    2522        /*Fetch parameters: */
    2623        iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
    27        
     24
    2825        /*Recover pointer: */
    29         nodes=*pnodes;
     26        Nodes* nodes=*pnodes;
    3027
    3128        /*Create nodes if they do not exist yet*/
     
    4037        for (i=0;i<numberofvertices;i++){
    4138                if(iomodel->my_vertices[i]){
    42                        
     39
    4340                        /*Add node to nodes dataset: */
    4441                        nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,EnthalpyAnalysisEnum));
     
    4946        /*Clean fetched data: */
    5047        iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
    51        
     48
    5249        /*Assign output pointer: */
    5350        *pnodes=nodes;
  • issm/trunk/src/c/modules/ModelProcessorx/Enthalpy/UpdateElementsEnthalpy.cpp

    r13395 r13975  
    5959        iomodel->FetchDataToInput(elements,VyEnum);
    6060        iomodel->FetchDataToInput(elements,VzEnum);
    61        
     61
    6262        /*Free data: */
    6363        iomodel->DeleteData(4,MeshElementsEnum,TemperatureEnum,WaterfractionEnum,PressureEnum);
  • issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateConstraintsHydrology.cpp

    r13395 r13975  
    1414void    CreateConstraintsHydrology(Constraints** pconstraints, IoModel* iomodel){
    1515
    16         /*Output*/
    17         Constraints *constraints = NULL;
    18 
    1916        /*Recover pointer: */
    20         constraints=*pconstraints;
     17        Constraints* constraints=*pconstraints;
    2118
    2219        /*Create constraints if they do not exist yet*/
    2320        if(!constraints) constraints = new Constraints();
    2421        IoModelToConstraintsx(constraints,iomodel,HydrologySpcwatercolumnEnum,HydrologyAnalysisEnum);
    25        
     22
    2623        /*Assign output pointer: */
    2724        *pconstraints=constraints;
  • issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateLoadsHydrology.cpp

    r13395 r13975  
    1313void    CreateLoadsHydrology(Loads** ploads, IoModel* iomodel){
    1414
    15         /*Intermediary*/
    16         int i;
    17 
    18         /*DataSet*/
    19         Loads*    loads    = NULL;
    20 
    2115        /*Recover pointer: */
    22         loads=*ploads;
     16        Loads* loads=*ploads;
    2317
    2418        /*Create loads if they do not exist yet*/
  • issm/trunk/src/c/modules/ModelProcessorx/Hydrology/CreateNodesHydrology.cpp

    r13395 r13975  
    2020        int    numberofvertices;
    2121
    22         /*DataSets: */
    23         Nodes*    nodes = NULL;
    24 
    2522        /*Fetch parameters: */
    2623        iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
    27        
     24
    2825        /*Recover pointer: */
    29         nodes=*pnodes;
     26        Nodes* nodes=*pnodes;
    3027
    3128        /*Create nodes if they do not exist yet*/
     
    4643        }
    4744        iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
    48        
     45
    4946        /*Assign output pointer: */
    5047        *pnodes=nodes;
  • issm/trunk/src/c/modules/ModelProcessorx/Hydrology/UpdateElementsHydrology.cpp

    r13395 r13975  
    1717
    1818        int    numberofelements;
    19        
     19
    2020        /*Fetch data needed: */
    2121        iomodel->Constant(&numberofelements,MeshNumberofelementsEnum);
  • issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateConstraintsMelting.cpp

    r13395 r13975  
    1313void    CreateConstraintsMelting(Constraints** pconstraints, IoModel* iomodel){
    1414
    15         /*Intermediary*/
    16         int i;
    17         int count;
    18        
    19         /*Intermediary*/
    20         Constraints* constraints = NULL;
    21 
    2215        /*Recover pointer: */
    23         constraints=*pconstraints;
     16        Constraints* constraints=*pconstraints;
    2417
    2518        /*Create constraints if they do not exist yet*/
  • issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateLoadsMelting.cpp

    r13395 r13975  
    1414
    1515        /*Intermediary*/
    16         int i;
    17         int    dim;
    18         int    numberofvertices;
    19 
    20         /*DataSet*/
    21         Loads*    loads    = NULL;
    22 
    23         /*Fetch parameters: */
     16        int dim;
     17        int numberofvertices;
    2418        iomodel->Constant(&dim,MeshDimensionEnum);
    2519        iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
     
    2923
    3024        /*Recover pointer: */
    31         loads=*ploads;
     25        Loads* loads=*ploads;
    3226
    3327        /*Create loads if they do not exist yet*/
     
    3832        CreateSingleNodeToElementConnectivity(iomodel);
    3933
    40         for (i=0;i<numberofvertices;i++){
     34        for(int i=0;i<numberofvertices;i++){
    4135                if((iomodel->my_vertices[i]==1)){
    4236                        if (reCast<int>(iomodel->Data(MeshVertexonbedEnum)[i])){
  • issm/trunk/src/c/modules/ModelProcessorx/Melting/CreateNodesMelting.cpp

    r13395 r13975  
    2020        int    numberofvertices;
    2121
    22         /*DataSets: */
    23         Nodes*    nodes = NULL;
    24        
    2522        /*Fetch parameters: */
    2623        iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
    2724
    2825        /*Recover pointer: */
    29         nodes=*pnodes;
     26        Nodes* nodes=*pnodes;
    3027
    3128        /*Create nodes if they do not exist yet*/
     
    4037
    4138                if(iomodel->my_vertices[i]){
    42                        
     39
    4340                        /*Add node to nodes dataset: */
    4441                        nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,MeltingAnalysisEnum));
  • issm/trunk/src/c/modules/ModelProcessorx/Melting/UpdateElementsMelting.cpp

    r13395 r13975  
    5555        iomodel->FetchDataToInput(elements,BasalforcingsMeltingRateEnum);
    5656        iomodel->FetchDataToInput(elements,PressureEnum);
    57        
     57
    5858        /*Free data: */
    5959        iomodel->DeleteData(1,MeshElementsEnum);
  • issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp

    r13395 r13975  
    2020
    2121        int   i,analysis_type,dim,verbose;
    22         bool  isthermal,isprognostic,isdiagnostic,isgroundingline,isenthalpy,autodiff;
    23        
     22        bool  isthermal,isprognostic,isdiagnostic,isgroundingline,isenthalpy;
     23
    2424        /*output: */
    2525        Elements    *elements    = NULL;
     
    3131        Parameters  *parameters  = NULL;
    3232
    33        
    3433        /*Initialize IoModel from input file*/
    3534        IoModel* iomodel = new IoModel(IOMODEL);
     
    4342        iomodel->Constant(&isdiagnostic,TransientIsdiagnosticEnum);
    4443        iomodel->Constant(&isgroundingline,TransientIsgroundinglineEnum);
    45         iomodel->Constant(&autodiff,AutodiffIsautodiffEnum);
    46 
    47         /*If we are running in AD mode, we need to declare our independent variables now, before
    48          *and prevent them from being erased during successive calls to iomodel->FetchData and
    49          iomodel->DeleteData:*/
    50         if(autodiff)iomodel->DeclareIndependents();
    5144
    5245        SetVerbosityLevel(verbose);
     
    7366                if(solution_type==SteadystateSolutionEnum && analysis_type==MeltingAnalysisEnum && isenthalpy==true) continue;
    7467                if(solution_type==SteadystateSolutionEnum && analysis_type==EnthalpyAnalysisEnum && isenthalpy==false) continue;
    75        
     68
    7669                if(VerboseMProcessor()) _pprintLine_("   creating datasets for analysis " << EnumToStringx(analysis_type));
    7770                CreateDataSets(&elements,&nodes,&vertices,&materials,&constraints,&loads,&parameters,iomodel,rootpath,solution_type,analysis_type,nummodels,i);
  • issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h

    r13395 r13975  
    109109void  UpdateCounters(IoModel* iomodel,Nodes** pnodes,Loads** ploads, Constraints** pconstraints);
    110110
    111 
    112111/*Distribution of dofs: */
    113112void DistributeNumDofs(DofIndexing* index,int analysis_type,IssmDouble* vertices_type);
  • issm/trunk/src/c/modules/ModelProcessorx/NodesPartitioning.cpp

    r13395 r13975  
    2222
    2323void  NodesPartitioning(bool** pmy_nodes,bool* my_elements, int* my_vertices, IoModel* iomodel, bool continuous){
    24        
     24
    2525        /*First thing, this is a new partition for a new analysis_type, therefore, to avoid a leak, erase the nodes partition that might come through pmy_nodes: */
    2626        xDelete<bool>(*pmy_nodes);
     
    5151}
    5252
    53 
    5453void  DiscontinuousGalerkinNodesPartitioning(bool** pmy_nodes,bool* my_elements, int* my_vertices, IoModel* iomodel){
    5554
     
    6261         * the nodes and the vertices. The vertices are similar to continuous galerkin, but the nodes partitioning involves edges, which mess up sorting of
    6362         * ids. */
    64        
     63
    6564        int i,j;
    6665        int    dim;
  • issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateConstraintsPrognostic.cpp

    r13395 r13975  
    1010void    CreateConstraintsPrognostic(Constraints** pconstraints, IoModel* iomodel){
    1111
     12        /*Fetch parameters: */
    1213        int stabilization;
    13        
    14         /*Fetch parameters: */
    1514        iomodel->Constant(&stabilization,PrognosticStabilizationEnum);
    1615
    17         /*Output*/
    18         Constraints *constraints = NULL;
    19 
    2016        /*Recover pointer: */
    21         constraints=*pconstraints;
     17        Constraints* constraints=*pconstraints;
    2218
    2319        /*Create constraints if they do not exist yet*/
  • issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateLoadsPrognostic.cpp

    r13395 r13975  
    2323        int numberofelements;
    2424
    25         /*DataSet*/
    26         Loads*    loads    = NULL;
    27        
    2825        /*Fetch parameters: */
    2926        iomodel->Constant(&stabilization,PrognosticStabilizationEnum);
     
    3229
    3330        /*Recover pointer: */
    34         loads=*ploads;
     31        Loads* loads=*ploads;
    3532
    3633        /*Create loads if they do not exist yet*/
  • issm/trunk/src/c/modules/ModelProcessorx/Prognostic/CreateNodesPrognostic.cpp

    r13395 r13975  
    2626        int    stabilization;
    2727
    28         /*DataSets: */
    29         Nodes*    nodes = NULL;
    30 
    3128        /*Fetch parameters: */
    3229        iomodel->Constant(&dim,MeshDimensionEnum);
     
    3633
    3734        /*Recover pointer: */
    38         nodes=*pnodes;
     35        Nodes* nodes=*pnodes;
    3936
    4037        /*Create nodes if they do not exist yet*/
  • issm/trunk/src/c/modules/ModelProcessorx/Prognostic/UpdateElementsPrognostic.cpp

    r13395 r13975  
    7373        if(issmbgradients){
    7474                iomodel->FetchDataToInput(elements,SurfaceforcingsHcEnum);
     75                iomodel->FetchDataToInput(elements,SurfaceforcingsHrefEnum);
     76                iomodel->FetchDataToInput(elements,SurfaceforcingsSmbrefEnum);
    7577                iomodel->FetchDataToInput(elements,SurfaceforcingsSmbPosMaxEnum);
    7678                iomodel->FetchDataToInput(elements,SurfaceforcingsSmbPosMinEnum);
  • issm/trunk/src/c/modules/ModelProcessorx/SortDataSets.cpp

    r13395 r13975  
    1414#include "../../EnumDefinitions/EnumDefinitions.h"
    1515#include "./ModelProcessorx.h"
    16 
    1716
    1817void SortDataSets(Elements** pelements,Nodes** pnodes,Vertices** pvertices, Loads** ploads, Materials** pmaterials, Constraints** pconstraints, Parameters** pparameters){
  • issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateConstraintsSurfaceSlope.cpp

    r13395 r13975  
    1313void    CreateConstraintsSurfaceSlope(Constraints** pconstraints, IoModel* iomodel){
    1414
    15         /*Output*/
    16         Constraints* constraints = NULL;
    17        
    1815        /*Recover pointer: */
    19         constraints=*pconstraints;
     16        Constraints* constraints=*pconstraints;
    2017
    2118        /*Create constraints if they do not exist yet*/
  • issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateLoadsSurfaceSlope.cpp

    r13395 r13975  
    1313void    CreateLoadsSurfaceSlope(Loads** ploads, IoModel* iomodel){
    1414
    15         /*DataSet*/
    16         Loads*    loads    = NULL;
    17 
    1815        /*Recover pointer: */
    19         loads=*ploads;
     16        Loads* loads=*ploads;
    2017
    2118        /*Create loads if they do not exist yet*/
  • issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/CreateNodesSurfaceSlope.cpp

    r13395 r13975  
    1616
    1717        /*Intermediary*/
    18         int i;
    1918        bool continuous_galerkin=true;
    2019        int    numberofvertices;
    21 
    22         /*DataSets: */
    23         Nodes*    nodes = NULL;
    2420
    2521        /*Fetch parameters: */
     
    2723
    2824        /*Recover pointer: */
    29         nodes=*pnodes;
     25        Nodes* nodes=*pnodes;
    3026
    3127        /*Create nodes if they do not exist yet*/
    3228        if(!nodes) nodes = new Nodes();
    33        
     29
    3430        /*Continuous Galerkin partition of nodes: */
    3531        NodesPartitioning(&iomodel->my_nodes,iomodel->my_elements,iomodel->my_vertices,iomodel,continuous_galerkin);
    36        
     32
    3733        /*First fetch data: */
    3834        iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
    3935
    40         for (i=0;i<numberofvertices;i++){
     36        for(int i=0;i<numberofvertices;i++){
     37                if(iomodel->my_vertices[i]){
    4138
    42                 if(iomodel->my_vertices[i]){
    43                        
    4439                        /*Add node to nodes dataset: */
    4540                        nodes->AddObject(new Node(iomodel->nodecounter+i+1,i,i+1,i,iomodel,SurfaceSlopeAnalysisEnum));
     
    5045        /*Clean fetched data: */
    5146        iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
    52        
     47
    5348        /*Assign output pointer: */
    5449        *pnodes=nodes;
  • issm/trunk/src/c/modules/ModelProcessorx/SurfaceSlope/UpdateElementsSurfaceSlope.cpp

    r13395 r13975  
    3737        iomodel->FetchDataToInput(elements,BedEnum);
    3838        iomodel->FetchDataToInput(elements,MaskElementonwaterEnum);
    39        
     39
    4040        if (dim==3){
    4141                iomodel->FetchDataToInput(elements,MeshElementonbedEnum);
    4242                iomodel->FetchDataToInput(elements,MeshElementonsurfaceEnum);
    4343        }
    44        
     44
    4545        /*Free data: */
    4646        iomodel->DeleteData(1,MeshElementsEnum);
  • issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateConstraintsThermal.cpp

    r13395 r13975  
    1414void    CreateConstraintsThermal(Constraints** pconstraints, IoModel* iomodel){
    1515
    16         /*Intermediary*/
    17         int i;
    18         int count;
     16        /*Fetch parameters: */
    1917        int    dim;
    20        
    21         /*Output*/
    22         Constraints* constraints = NULL;
    23 
    24         /*Fetch parameters: */
    2518        iomodel->Constant(&dim,MeshDimensionEnum);
    2619
    2720        /*Recover pointer: */
    28         constraints=*pconstraints;
     21        Constraints* constraints=*pconstraints;
    2922
    3023        /*Create constraints if they do not exist yet*/
  • issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateLoadsThermal.cpp

    r13395 r13975  
    1717        int    dim;
    1818        int    numberofvertices;
    19 
    20         /*DataSet*/
    21         Loads*    loads    = NULL;
    2219        Pengrid*    pengrid  = NULL;
    2320
    2421        /*Recover pointer: */
    25         loads=*ploads;
     22        Loads* loads=*ploads;
    2623
    2724        /*Fetch parameters: */
     
    4037
    4138        for (i=0;i<numberofvertices;i++){
    42        
     39
    4340                /*keep only this partition's nodes:*/
    4441                if((iomodel->my_vertices[i]==1)){
  • issm/trunk/src/c/modules/ModelProcessorx/Thermal/CreateNodesThermal.cpp

    r13395 r13975  
    1616
    1717        /*Intermediary*/
    18         int i;
    1918        bool continuous_galerkin=true;
    20         int    numberofvertices;
    21 
    22         /*DataSets: */
    23         Nodes*    nodes = NULL;
    2419
    2520        /*Fetch parameters: */
     21        int    numberofvertices;
    2622        iomodel->Constant(&numberofvertices,MeshNumberofverticesEnum);
    2723
    2824        /*Recover pointer: */
    29         nodes=*pnodes;
     25        Nodes* nodes=*pnodes;
    3026
    3127        /*Create nodes if they do not exist yet*/
     
    3834        iomodel->FetchData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
    3935
    40         for (i=0;i<numberofvertices;i++){
    41 
     36        for(int i=0;i<numberofvertices;i++){
    4237                if(iomodel->my_vertices[i]){
    4338                        /*Add node to nodes dataset: */
     
    4944        /*Clean fetched data: */
    5045        iomodel->DeleteData(6,MeshVertexonbedEnum,MeshVertexonsurfaceEnum,MaskVertexongroundediceEnum,MaskVertexonfloatingiceEnum,FlowequationVertexEquationEnum,MaskVertexonwaterEnum);
    51        
     46
    5247        /*Assign output pointer: */
    5348        *pnodes=nodes;
  • issm/trunk/src/c/modules/ModelProcessorx/Thermal/UpdateElementsThermal.cpp

    r13395 r13975  
    6060        iomodel->FetchDataToInput(elements,VyEnum);
    6161        iomodel->FetchDataToInput(elements,VzEnum);
    62        
     62
    6363        if(dakota_analysis){
    6464                elements->InputDuplicate(TemperatureEnum,QmuTemperatureEnum);
  • issm/trunk/src/c/modules/ModelProcessorx/UpdateCounters.cpp

    r13395 r13975  
    2626        constraints=*pconstraints;
    2727
    28 
    2928        if(nodes) iomodel->nodecounter=nodes->NumberOfNodes();
    3029        else iomodel->nodecounter=0;
     
    3231        if(loads)iomodel->loadcounter=loads->NumberOfLoads();
    3332        else iomodel->loadcounter=0;
    34        
     33
    3534        if(constraints)iomodel->constraintcounter=constraints->NumberOfConstraints();
    3635        else iomodel->constraintcounter=0;
  • issm/trunk/src/c/modules/NodalValuex/NodalValuex.cpp

    r13395 r13975  
    1212void NodalValuex( IssmDouble* pnodalvalue, int natureofdataenum,Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,bool process_units){
    1313
    14         extern int my_rank;
     14        int my_rank;
    1515        int i;
    1616        int index;
     
    2121        int cpu_found;
    2222
     23        /*Get my_rank:*/
     24        my_rank=IssmComm::GetRank();
     25
    2326        /*retrieve element we are interested in: */
    2427        parameters->FindParam(&index,IndexEnum);
     
    2730         *element, figure out  if they hold the vertex, and the data. If so, return it: */
    2831        for(i=0;i<elements->Size();i++){
    29                 Element* element=(Element*)elements->GetObjectByOffset(i);
     32                Element* element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    3033                found=element->NodalValue(&value,index,natureofdataenum,process_units);
    3134                if (found){
     
    3740        /*Broadcast whether we found the element: */
    3841        #ifdef _HAVE_MPI_
    39         MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
     42        MPI_Allreduce ( &found,&sumfound,1,MPI_INT,MPI_SUM,IssmComm::GetComm());
    4043        if(!sumfound)_error_("could not find element with vertex with id" << index << " to compute nodal value " << EnumToStringx(natureofdataenum));
    4144        #endif
     
    4346        /*Broadcast and plug into response: */
    4447        #ifdef _HAVE_MPI_
    45         MPI_Allreduce ( &cpu_found,&cpu_found,1,MPI_INT,MPI_MAX,MPI_COMM_WORLD);
    46         MPI_Bcast(&value,1,MPI_DOUBLE,cpu_found,MPI_COMM_WORLD);
     48        MPI_Allreduce ( &cpu_found,&cpu_found,1,MPI_INT,MPI_MAX,IssmComm::GetComm());
     49        MPI_Bcast(&value,1,MPI_DOUBLE,cpu_found,IssmComm::GetComm());
    4750        #else
    4851        value=cpu_found;
  • issm/trunk/src/c/modules/NodalValuex/NodalValuex.h

    r13395 r13975  
    1313
    1414#endif  /* _NODALVALUEX_H */
    15 
  • issm/trunk/src/c/modules/NodeConnectivityx/NodeConnectivityx.cpp

    r13395 r13975  
    3434        double* connectivity=NULL;
    3535
    36 
    37 
    3836        /*Allocate connectivity: */
    3937        connectivity=xNewZeroInit<double>(nods*width);
     
    4644
    4745                for(i=0;i<3;i++){
    48                
     46
    4947                        node=(int)*(elements+n*3+i); //already matlab indexed, elements comes directly from the workspace.
    5048                        index=node-1;
    5149
    5250                        num_elements=(int)*(connectivity+width*index+maxels); //retrieve number of elements already  plugged into the connectivity of this node.
    53                        
     51
    5452                        already_plugged=0;
    5553                        for(j=0;j<num_elements;j++){
     
    6462                        *(connectivity+width*index+num_elements)=element;
    6563                        *(connectivity+width*index+maxels)=(double)(num_elements+1);
    66                        
     64
    6765                }
    6866        }
  • issm/trunk/src/c/modules/NodeConnectivityx/NodeConnectivityx.h

    r1105 r13975  
    1010
    1111#endif  /* _NODECONNECTIVITYX_H */
    12 
  • issm/trunk/src/c/modules/NodesDofx/NodesDofx.cpp

    r8816 r13975  
    1414        int noerr=1;
    1515        int found=0;
    16         int i;
    17        
     16
    1817        /*Do we have any nodes for this analysis type? :*/
    1918        if(nodes->NumberOfNodes(configuration_type)){
  • issm/trunk/src/c/modules/Orthx/Orthx.cpp

    r13395 r13975  
    66
    77void    Orthx( Vector<IssmDouble>** pnewgradj, Vector<IssmDouble>* gradj, Vector<IssmDouble>* oldgradj){
    8        
     8
    99        /*output: */
    1010        Vector<IssmDouble>* newgradj=NULL;
    1111
    1212        /*intermediary:*/
    13         IssmDouble norm_new,norm_old,dot_product;;
     13        IssmDouble norm_old,dot_product;;
    1414
    1515        /*Initialize output*/
  • issm/trunk/src/c/modules/Orthx/Orthx.h

    r13395 r13975  
    1414
    1515#endif  /* _ORTHX_H */
    16 
  • issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.cpp

    r13395 r13975  
    1515#include "../../io/io.h"
    1616#include "../../classes/objects/objects.h"
    17                
     17
    1818void OutputResultsx(Elements* elements, Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Results* results){
    1919
    20         extern int  my_rank;
     20        int         my_rank;
    2121        FILE       *fid                     = NULL;
    2222        char       *outputfilename          = NULL;
     
    2626        char*       solutiontypestring      = NULL;
    2727        bool        dakota_analysis         = false;
    28        
     28
    2929        /*retrieve parameters: */
    3030        parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
     31
     32        /*recover my_rank:*/
     33        my_rank=IssmComm::GetRank();
    3134
    3235        if(dakota_analysis){
     
    5154        /*Now, open file for writing, if not already done: */
    5255        if(!parameters->Exist(OutputFilePointerEnum)){
    53                
     56
    5457                /*We don't have a file pointer. Retrieve the output file name and open it for writing:*/
    5558                parameters->FindParam(&outputfilename,OutputfilenameEnum);
     
    6972                }
    7073                xDelete<char>(outputfilename);
    71                
     74
    7275                /*Add file pointer in parameters for further calls to OutputResultsx: */
    7376                parameters->SetParam(fid,OutputFilePointerEnum);
  • issm/trunk/src/c/modules/OutputResultsx/OutputResultsx.h

    r12330 r13975  
    1717
    1818#endif  /* _OUTPUTRESULTS_H */
    19 
  • issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.cpp

    r4214 r13975  
    1717
    1818        /*Allocate grad_g: */
    19         riftproperties=NewVec(numrifts);
     19        riftproperties=NewVec(numrifts,IssmComm::GetComm());
    2020
    2121        /*Compute rift properties : */
  • issm/trunk/src/c/modules/OutputRiftsx/OutputRiftsx.h

    r4236 r13975  
    1212
    1313#endif  /* _OUTPUTRIFTSX_H */
    14 
  • issm/trunk/src/c/modules/ParsePetscOptionsx/ParsePetscOptionsx.cpp

    r13395 r13975  
    2323
    2424        char line [1000];
    25         extern int my_rank;
     25        int my_rank;
    2626        int i;
    2727
     
    3434        char* catstring=NULL;
    3535        int   stringlength;
     36
     37        /*Get my_rank:*/
     38        my_rank=IssmComm::GetRank();
    3639
    3740        if(my_rank==0){
     
    5659                numanalyses=0;
    5760                while ( fgets(line, sizeof line, fid) ){
    58                
     61
    5962                        /*skip comments and empty lines: */
    6063                        if ((line[0]=='%') || (line[0]=='\n') || (line[0]==' ') || (line[0]=='\t') || (line[0]=='\r'))continue;
    61                
     64
    6265                        /*Get rid of end of line: */
    6366                        line[strlen(line)-1]='\0';
    64                
     67
    6568                        if (line[0]=='+'){ /*this is the analysis line: */
    6669                                analyses[numanalyses]=StringToEnumx(&line[1]);  //skip the '+'
     
    9699        /*Ok, broadcast to other cpus: */
    97100        #ifdef _HAVE_MPI_
    98         MPI_Bcast(&numanalyses,1,MPI_INT,0,MPI_COMM_WORLD);
     101        MPI_Bcast(&numanalyses,1,MPI_INT,0,IssmComm::GetComm());
    99102        if(my_rank!=0){
    100103                analyses=xNew<IssmPDouble>(numanalyses);
    101104                strings=xNew<char*>(numanalyses);
    102105        }
    103         MPI_Bcast(analyses,numanalyses,MPI_DOUBLE,0,MPI_COMM_WORLD);
     106        MPI_Bcast(analyses,numanalyses,MPI_DOUBLE,0,IssmComm::GetComm());
    104107        #endif
    105108        for(i=0;i<numanalyses;i++){
     
    110113                if(my_rank==0)stringlength=(strlen(string)+1)*sizeof(char);
    111114                #ifdef _HAVE_MPI_
    112                 MPI_Bcast(&stringlength,1,MPI_INT,0,MPI_COMM_WORLD);
     115                MPI_Bcast(&stringlength,1,MPI_INT,0,IssmComm::GetComm());
    113116                if(my_rank!=0)string=xNew<char>(stringlength);
    114                 MPI_Bcast(string,stringlength,MPI_CHAR,0,MPI_COMM_WORLD);
     117                MPI_Bcast(string,stringlength,MPI_CHAR,0,IssmComm::GetComm());
    115118                if(my_rank!=0)strings[i]=string;
    116119                #endif
  • issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsx.h

    r13395 r13975  
    22        PointCloudFindNeighborsx.h
    33*/
    4 
    54
    65#ifndef _POINTCLOUDFLAGNEIGHBORSX_H
     
    2625void* PointCloudFindNeighborsxt(void* vPointCloudFindNeighborsThreadStruct);
    2726
    28 
    2927#endif /* _POINTCLOUDFLAGNEIGHBORSX_H */
    30 
  • issm/trunk/src/c/modules/PointCloudFindNeighborsx/PointCloudFindNeighborsxt.cpp

    r13395 r13975  
    2424        my_thread=handle->id;
    2525        num_threads=handle->num;
    26        
     26
    2727        /*recover parameters :*/
    2828        x=gate->x;
     
    5757                        if (j==i)continue;
    5858                        distance=sqrt(pow(x[i]-x[j],2)+ pow(y[i]-y[j],2));
    59                        
     59
    6060                        if(distance<=mindistance){
    6161
     
    7474        /*Free ressources:*/
    7575        xDelete<bool>(already);
    76        
     76
    7777        return NULL;
    7878}
  • issm/trunk/src/c/modules/PositiveDegreeDayx/PositiveDegreeDayx.cpp

    r12706 r13975  
    3535  IssmDouble PDup, PDCUT = 2.0;    // PDcut: rain/snow cutoff temperature (C)
    3636  IssmDouble tstar; // monthly mean surface temp
    37  
     37
    3838  IssmDouble* pdds=NULL;
    3939  IssmDouble* pds=NULL;
    4040  Element* element = NULL;
    41  
     41
    4242  pdds=xNew<IssmDouble>(NPDMAX+1);
    4343  pds=xNew<IssmDouble>(NPDCMAX+1);
    44  
     44
    4545  // initialize PDD (creation of a lookup table)
    4646  tstep = 0.1;
     
    5555
    5656  itm = reCast<int,IssmDouble>((2*siglim/DT + 1.5));
    57  
     57
    5858  if (itm >= NPDMAX){
    5959    _printLine_("increase NPDMAX in massBalance.cpp");
     
    7373  }
    7474  pdds[itm+1] = siglim + DT;
    75  
     75
    7676  //*********compute PD(T) : snow/precip fraction. precipitation falling as snow
    7777  tstepc = 0.1;
     
    100100  pds[itm+1] = 0.;
    101101  //     *******END initialize PDD
    102  
     102
    103103  for(i=0;i<elements->Size();i++){
    104     element=(Element*)elements->GetObjectByOffset(i);
     104    element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    105105    element->PositiveDegreeDay(pdds,pds,signorm);
    106106  }
     
    108108  xDelete<IssmDouble>(pdds);
    109109  xDelete<IssmDouble>(pds);
    110  
     110
    111111}
  • issm/trunk/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.cpp

    r3913 r13975  
    1515        RecursivePropagation(pool, connectivity,index, flags);
    1616}
    17 
    1817
    1918void RecursivePropagation(double* pool, double* connectivity, int index, double* flags){
  • issm/trunk/src/c/modules/PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h

    r4236 r13975  
    1111
    1212#endif  /* _PROPAGATEFLAGSFROMCONNECTIVITYX_H */
    13 
  • issm/trunk/src/c/modules/Reduceloadx/Reduceloadx.cpp

    r13395 r13975  
    2020        int         global_m,global_n;
    2121        bool        fromlocalsize = true;
    22         int         verbose;
     22        bool        oldalloc  = false;
    2323
    2424        if(VerboseModule()) _pprintLine_("   Dirichlet lifting applied to load vector");
     
    3232                /*pf = pf - Kfs * y_s;*/
    3333                Kfs->GetLocalSize(&Kfsm,&Kfsn);
    34                 Kfsy_s=new Vector<IssmDouble>(Kfsm,fromlocalsize);
     34                if(oldalloc)
     35                 Kfsy_s=new Vector<IssmDouble>(Kfsm,fromlocalsize);
     36                else
     37                 Kfsy_s=new Vector<IssmDouble>(Kfsm,global_m);
     38
    3539                if (flag_ys0){
    3640
     
    4953        }
    5054
    51 
    5255        /*Free ressources and return*/
    5356        xdelete(&y_s0);
  • issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.cpp

    r13395 r13975  
    55
    66#include "./Reducevectorgtofx.h"
    7  
     7
    88void Reducevectorgtofx(Vector<IssmDouble>** puf, Vector<IssmDouble>* ug, Nodes* nodes,Parameters* parameters){
    99
     
    1212
    1313        /*variables: */
    14         int i;
    15         int configuration_type;
    16         int fsize;
    17         IssmDouble* ug_serial=NULL;
     14        int         configuration_type;
     15        int         fsize;
     16        IssmDouble *ug_serial = NULL;
     17        bool        oldalloc  = false;
    1818
    1919        /*first figure out fsize: */
    2020        parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
    2121        fsize=nodes->NumberOfDofs(configuration_type,FsetEnum);
     22
     23        int    analysis_type;
     24        parameters->FindParam(&analysis_type,AnalysisTypeEnum);
     25        int flocalsize = nodes->NumberOfDofsLocal(analysis_type,FsetEnum);
    2226
    2327        if(fsize==0){
     
    2630        else{
    2731                /*allocate: */
    28                 uf=new Vector<IssmDouble>(fsize);
     32                if(oldalloc)
     33                 uf=new Vector<IssmDouble>(fsize);
     34                else
     35                 uf=new Vector<IssmDouble>(flocalsize,fsize);
    2936
    3037                if(nodes->NumberOfNodes(configuration_type)){
     
    3441
    3542                        /*Go through all nodes, and ask them to retrieve values from ug, and plug them into uf: */
    36                         for(i=0;i<nodes->Size();i++){
     43                        for(int i=0;i<nodes->Size();i++){
    3744
    3845                                Node* node=(Node*)nodes->GetObjectByOffset(i);
  • issm/trunk/src/c/modules/Reducevectorgtofx/Reducevectorgtofx.h

    r13395 r13975  
    1313
    1414#endif  /* _REDUCEVECTORGTOFX_H */
    15 
  • issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.cpp

    r13395 r13975  
    2121        ssize=nodes->NumberOfDofs(configuration_type,SsetEnum);
    2222
     23        int analysis_type;
     24        parameters->FindParam(&analysis_type,AnalysisTypeEnum);
     25        int slocalsize = nodes->NumberOfDofsLocal(analysis_type,SsetEnum);
     26
     27        bool oldalloc = false;
     28
    2329        if(ssize==0){
    2430                ys=NULL;
     
    2632        else{
    2733                /*allocate: */
    28                 ys=new Vector<IssmDouble>(ssize);
     34                if(oldalloc)
     35                 ys=new Vector<IssmDouble>(ssize);
     36                else
     37                 ys=new Vector<IssmDouble>(slocalsize,ssize);
    2938
    3039                if(nodes->NumberOfNodes(configuration_type)){
  • issm/trunk/src/c/modules/Reducevectorgtosx/Reducevectorgtosx.h

    r13395 r13975  
    1313
    1414#endif  /* _REDUCEVECTORGTOSX_H */
    15 
  • issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.cpp

    r13395 r13975  
    1212
    1313void ResetConstraintsx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads,Materials* materials,  Parameters* parameters){
    14 
    15         int i;
    16 
    17         extern int num_procs;
    18         extern int my_rank;
    1914
    2015        /*output: */
  • issm/trunk/src/c/modules/ResetConstraintsx/ResetConstraintsx.h

    r13395 r13975  
    1414
    1515#endif  /* _RESETCONSTRAINTSX_H */
    16 
  • issm/trunk/src/c/modules/ResetCoordinateSystemx/ResetCoordinateSystemx.cpp

    r10440 r13975  
    1313
    1414        for (int i=0;i<elements->Size();i++){
    15                 element=(Element*)elements->GetObjectByOffset(i);
     15                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    1616                element->ResetCoordinateSystem();
    1717        }
  • issm/trunk/src/c/modules/RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.cpp

    r13395 r13975  
    2222        /*Compute Misfit: */
    2323        for (i=0;i<elements->Size();i++){
    24                 element=(Element*)elements->GetObjectByOffset(i);
     24                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2525                J+=element->RheologyBbarAbsGradient(process_units,weight_index);
    2626        }
     
    2828        /*Sum all J from all cpus of the cluster:*/
    2929        #ifdef _HAVE_MPI_
    30         MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
    31         MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
     30        MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
     31        MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
    3232        J=J_sum;
    3333        #endif
  • issm/trunk/src/c/modules/Scotchx/Scotchx.h

    r13395 r13975  
    55#ifndef _SCOTCHX_H
    66#define _SCOTCHX_H
    7 
    87
    98#undef __FUNCT__
  • issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp

    r13395 r13975  
    2929
    3030void SetControlInputsFromVectorx(Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials, Parameters* parameters,Vector<IssmDouble>* vector){
    31        
     31
    3232        IssmDouble* serial_vector=NULL;
    3333
  • issm/trunk/src/c/modules/Shp2Kmlx/Shp2Kmlx.cpp

    r13395 r13975  
    1515
    1616        #ifdef _HAVE_SHAPELIB_ //only works if Shapelib library has been compiled in.
    17        
     17
    1818        double  cm,sp;
    1919
     
    3333
    3434        #ifdef _HAVE_SHAPELIB_ //only works if Shapelib library has been compiled in.
    35        
     35
    3636        int     i,j,k,iret=0;
    3737        int     lwidth=1;
     
    611611        #endif
    612612}
    613 
  • issm/trunk/src/c/modules/SmbGradientsx/SmbGradientsx.cpp

    r12706 r13975  
    1818
    1919  int    i;
    20  
     20
    2121  Element* element = NULL;
    22  
     22
    2323  for(i=0;i<elements->Size();i++){
    24     element=(Element*)elements->GetObjectByOffset(i);
     24    element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2525    element->SmbGradients();
    2626  }
  • issm/trunk/src/c/modules/Solverx/DofTypesToIndexSet.cpp

    r12706 r13975  
    1212#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
    1313#endif
    14        
     14
    1515void DofTypesToIndexSet(IS* pisv, IS* pisp, Vec df,int typeenum){
    1616
     
    6262                }
    6363                VecRestoreArray(df,&df_local);
    64                
     64
    6565                /*Create indices sets: */
    6666                #if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
    67                 ISCreateGeneral(PETSC_COMM_WORLD,pressure_num,pressure_indices,&isp);
    68                 ISCreateGeneral(PETSC_COMM_WORLD,velocity_num,velocity_indices,&isv);
     67                ISCreateGeneral(IssmComm::GetComm(),pressure_num,pressure_indices,&isp);
     68                ISCreateGeneral(IssmComm::GetComm(),velocity_num,velocity_indices,&isv);
    6969                #else
    70                 ISCreateGeneral(PETSC_COMM_WORLD,pressure_num,pressure_indices,PETSC_COPY_VALUES,&isp);
    71                 ISCreateGeneral(PETSC_COMM_WORLD,velocity_num,velocity_indices,PETSC_COPY_VALUES,&isv);
     70                ISCreateGeneral(IssmComm::GetComm(),pressure_num,pressure_indices,PETSC_COPY_VALUES,&isp);
     71                ISCreateGeneral(IssmComm::GetComm(),velocity_num,velocity_indices,PETSC_COPY_VALUES,&isv);
    7272                #endif
    7373        }
  • issm/trunk/src/c/modules/Solverx/Solverx.cpp

    r13395 r13975  
    1515
    1616void    Solverx(Vector<IssmDouble>** puf, Matrix<IssmDouble>* Kff, Vector<IssmDouble>* pf, Vector<IssmDouble>* uf0,Vector<IssmDouble>* df, Parameters* parameters){
    17 
    18         /*Intermediary: */
    19         int analysis_type;
    2017
    2118        /*output: */
  • issm/trunk/src/c/modules/Solverx/Solverx.h

    r13395 r13975  
    2727void SolverxSeq(IssmPDouble *X, IssmPDouble *A, IssmPDouble *B,int n);
    2828
    29 #ifdef _HAVE_ADOLC_
     29#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
    3030void SolverxSeq(IssmDouble *X,IssmDouble *A,IssmDouble *B,int n, Parameters* parameters);
    3131// call back functions:
     
    3838
    3939#endif  /* _SOLVERX_H */
    40 
  • issm/trunk/src/c/modules/Solverx/SolverxPetsc.cpp

    r13395 r13975  
    2020        Vec uf0_vector = NULL;
    2121        Vec df_vector  = NULL;
    22        
     22
    2323        if(uf0) uf0_vector = uf0->vector;
    2424        if(df)  df_vector  = df->vector;
     
    3636        /*Intermediary: */
    3737        int        local_m,local_n,global_m,global_n;
    38         int        analysis_type;
    3938
    4039        /*Solver */
     
    7069        MatGetSize(Kff,&global_m,&global_n); _assert_(global_m==global_m);
    7170        if(!global_n){
    72                 *puf=NewVec(0); return;
     71                *puf=NewVec(0,IssmComm::GetComm()); return;
    7372        }
    7473
     
    8685        }
    8786        else{
    88                 MatGetLocalSize(Kff,&local_m,&local_n);uf=NewVec(local_n,fromlocalsize);
     87                MatGetLocalSize(Kff,&local_m,&local_n);uf=NewVec(local_n,IssmComm::GetComm(),fromlocalsize);
    8988        }
    9089
     
    102101
    103102        /*Prepare solver*/
    104         KSPCreate(MPI_COMM_WORLD,&ksp);
     103        KSPCreate(IssmComm::GetComm(),&ksp);
    105104        KSPSetOperators(ksp,Kff,Kff,DIFFERENT_NONZERO_PATTERN);
    106105        KSPSetFromOptions(ksp);
     
    148147        if(VerboseSolver())KSPView(ksp,PETSC_VIEWER_STDOUT_WORLD);
    149148        KSPSolve(ksp,pf,uf);
    150        
     149
    151150        /*Check convergence*/
    152151        KSPGetIterationNumber(ksp,&iteration_number);
     
    155154        /*Free resources:*/
    156155        KSPFree(&ksp);
    157                
     156
    158157        /*Assign output pointers:*/
    159158        *puf=uf;
  • issm/trunk/src/c/modules/Solverx/SolverxSeq.cpp

    r13395 r13975  
    1212#include "./Solverx.h"
    1313#include "../../shared/shared.h"
     14#include "../../classes/classes.h"
    1415#include "../../include/include.h"
    1516#include "../../io/io.h"
     
    1920#endif
    2021
    21 #ifdef _HAVE_ADOLC_
    22 #include "../../shared/Numerics/adolc_edf.h"
    23 #endif
    24 
    2522void SolverxSeq(SeqVec<IssmDouble>** puf,SeqMat<IssmDouble>* Kff, SeqVec<IssmDouble>* pf, Parameters* parameters){/*{{{*/
    2623
    2724#ifdef _HAVE_GSL_
    2825        /*Intermediary: */
    29         int M,N,N2,s;
     26        int M,N,N2;
    3027        SeqVec<IssmDouble> *uf = NULL;
    3128
     
    3532        if(N!=N2)_error_("Right hand side vector of size " << N2 << ", when matrix is of size " << M << "-" << N << " !");
    3633        if(M!=N)_error_("Stiffness matrix should be square!");
     34#ifdef _HAVE_ADOLC_
     35        ensureContiguousLocations(N);
     36#endif
    3737        IssmDouble *x  = xNew<IssmDouble>(N);
    38 
    3938#ifdef _HAVE_ADOLC_
    4039        SolverxSeq(x,Kff->matrix,pf->vector,N,parameters);
     
    6968#ifdef _HAVE_ADOLC_
    7069int EDF_for_solverx(int n, IssmPDouble *x, int m, IssmPDouble *y){ /*{{{*/
    71     SolverxSeq(y,x, x+m*m, m); // x is where the matrix starts, x+m*m is where the right-hand side starts
    72     return 0;
     70        SolverxSeq(y,x, x+m*m, m); // x is where the matrix starts, x+m*m is where the right-hand side starts
     71        return 0;
    7372} /*}}}*/
    7473int EDF_fos_forward_for_solverx(int n, IssmPDouble *inVal, IssmPDouble *inDeriv, int m, IssmPDouble *outVal, IssmPDouble *outDeriv) { /*{{{*/
    7574#ifdef _HAVE_GSL_
    76   // the matrix will be modified by LU decomposition. Use gsl_A copy
    77   double* Acopy = xNew<double>(m*m);
    78   xMemCpy(Acopy,inVal,m*m);
    79   /*Initialize gsl matrices and vectors: */
    80   gsl_matrix_view gsl_A = gsl_matrix_view_array (Acopy,m,m);
    81   gsl_vector_view gsl_b = gsl_vector_view_array (inVal+m*m,m); // the right hand side starts at address inVal+m*m
    82   gsl_permutation *perm_p = gsl_permutation_alloc (m);
    83   int  signPerm;
    84   // factorize
    85   gsl_linalg_LU_decomp (&gsl_A.matrix, perm_p, &signPerm);
    86   gsl_vector *gsl_x_p = gsl_vector_alloc (m);
    87   // solve for the value
    88   gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_b.vector, gsl_x_p);
    89   /*Copy result*/
    90   xMemCpy(outVal,gsl_vector_ptr(gsl_x_p,0),m);
    91   gsl_vector_free(gsl_x_p);
    92   // solve for the derivatives acc. to A * dx = r  with r=db - dA * x
    93   // compute the RHS
    94   double* r=xNew<double>(m);
    95   for (int i=0; i<m; i++) {
    96     r[i]=inDeriv[m*m+i]; // this is db[i]
    97     for (int j=0;j<m; j++) {
    98       r[i]-=inDeriv[i*m+j]*outVal[j]; // this is dA[i][j]*x[j]
    99     }
    100   }
    101   gsl_vector_view gsl_r=gsl_vector_view_array(r,m);
    102   gsl_vector *gsl_dx_p = gsl_vector_alloc(m);
    103   gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_r.vector, gsl_dx_p);
    104   xMemCpy(outDeriv,gsl_vector_ptr(gsl_dx_p,0),m);
    105   gsl_vector_free(gsl_dx_p);
    106   xDelete(r);
    107   gsl_permutation_free(perm_p);
    108   xDelete(Acopy);
    109   #endif
    110   return 0;
     75        //  for (int i=0; i<m*m; ++i) std::cout << "EDF_fos_forward_for_solverx A["<< i << "]=" << inVal[i] << std::endl;
     76        //  for (int i=0; i<m; ++i) std::cout << "EDF_fos_forward_for_solverx b["<< i << "]=" << inVal[i+m*m] << std::endl;
     77        // the matrix will be modified by LU decomposition. Use gsl_A copy
     78        double* Acopy = xNew<double>(m*m);
     79        xMemCpy(Acopy,inVal,m*m);
     80        /*Initialize gsl matrices and vectors: */
     81        gsl_matrix_view gsl_A = gsl_matrix_view_array (Acopy,m,m);
     82        gsl_vector_view gsl_b = gsl_vector_view_array (inVal+m*m,m); // the right hand side starts at address inVal+m*m
     83        gsl_permutation *perm_p = gsl_permutation_alloc (m);
     84        int  signPerm;
     85        // factorize
     86        gsl_linalg_LU_decomp (&gsl_A.matrix, perm_p, &signPerm);
     87        gsl_vector *gsl_x_p = gsl_vector_alloc (m);
     88        // solve for the value
     89        gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_b.vector, gsl_x_p);
     90        /*Copy result*/
     91        xMemCpy(outVal,gsl_vector_ptr(gsl_x_p,0),m);
     92        gsl_vector_free(gsl_x_p);
     93        //  for (int i=0; i<m; ++i) std::cout << "EDF_fos_forward_for_solverx x["<< i << "]=" << outVal[i] << std::endl;
     94        // solve for the derivatives acc. to A * dx = r  with r=db - dA * x
     95        // compute the RHS
     96        double* r=xNew<double>(m);
     97        for (int i=0; i<m; i++) {
     98                r[i]=inDeriv[m*m+i]; // this is db[i]
     99                for (int j=0;j<m; j++) {
     100                        r[i]-=inDeriv[i*m+j]*outVal[j]; // this is dA[i][j]*x[j]
     101                }
     102        }
     103        gsl_vector_view gsl_r=gsl_vector_view_array(r,m);
     104        gsl_vector *gsl_dx_p = gsl_vector_alloc(m);
     105        gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_r.vector, gsl_dx_p);
     106        xMemCpy(outDeriv,gsl_vector_ptr(gsl_dx_p,0),m);
     107        gsl_vector_free(gsl_dx_p);
     108        xDelete(r);
     109        gsl_permutation_free(perm_p);
     110        xDelete(Acopy);
     111#endif
     112        return 0;
    111113} /*}}}*/
    112114int EDF_fov_forward_for_solverx(int n, IssmPDouble *inVal, int directionCount, IssmPDouble **inDeriv, int m, IssmPDouble *outVal, IssmPDouble **outDeriv) { /*{{{*/
    113115#ifdef _HAVE_GSL_
    114   // the matrix will be modified by LU decomposition. Use gsl_A copy
    115   double* Acopy = xNew<double>(m*m);
    116   xMemCpy(Acopy,inVal,m*m);
    117   /*Initialize gsl matrices and vectors: */
    118   gsl_matrix_view gsl_A = gsl_matrix_view_array (Acopy,m,m);
    119   gsl_vector_view gsl_b = gsl_vector_view_array (inVal+m*m,m); // the right hand side starts at address inVal+m*m
    120   gsl_permutation *perm_p = gsl_permutation_alloc (m);
    121   int  signPerm;
    122   // factorize
    123   gsl_linalg_LU_decomp (&gsl_A.matrix, perm_p, &signPerm);
    124   gsl_vector *gsl_x_p = gsl_vector_alloc (m);
    125   // solve for the value
    126   gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_b.vector, gsl_x_p);
    127   /*Copy result*/
    128   xMemCpy(outVal,gsl_vector_ptr(gsl_x_p,0),m);
    129   gsl_vector_free(gsl_x_p);
    130   // solve for the derivatives acc. to A * dx = r  with r=db - dA * x
    131   double* r=xNew<double>(m);
    132   gsl_vector *gsl_dx_p = gsl_vector_alloc(m);
    133   for (int dir=0;dir<directionCount;++dir) {
    134     // compute the RHS
    135     for (int i=0; i<m; i++) {
    136       r[i]=inDeriv[m*m+i][dir]; // this is db[i]
    137       for (int j=0;j<m; j++) {
    138         r[i]-=inDeriv[i*m+j][dir]*outVal[j]; // this is dA[i][j]*x[j]
    139       }
    140     }
    141     gsl_vector_view gsl_r=gsl_vector_view_array(r,m);
    142     gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_r.vector, gsl_dx_p);
    143     // reuse r
    144     xMemCpy(r,gsl_vector_ptr(gsl_dx_p,0),m);
    145     for (int i=0; i<m; i++) {
    146       outDeriv[i][dir]=r[i];
    147     }
    148   }
    149   gsl_vector_free(gsl_dx_p);
    150   xDelete(r);
    151   gsl_permutation_free(perm_p);
    152   xDelete(Acopy);
    153   #endif
    154   return 0;
    155 }
    156 /*}}}*/
    157 int EDF_fos_reverse_for_solverx(int m, double *dp_U, int n, double *dp_Z) { /*{{{*/
    158   return 0;
     116        // the matrix will be modified by LU decomposition. Use gsl_A copy
     117        double* Acopy = xNew<double>(m*m);
     118        xMemCpy(Acopy,inVal,m*m);
     119        /*Initialize gsl matrices and vectors: */
     120        gsl_matrix_view gsl_A = gsl_matrix_view_array (Acopy,m,m);
     121        gsl_vector_view gsl_b = gsl_vector_view_array (inVal+m*m,m); // the right hand side starts at address inVal+m*m
     122        gsl_permutation *perm_p = gsl_permutation_alloc (m);
     123        int  signPerm;
     124        // factorize
     125        gsl_linalg_LU_decomp (&gsl_A.matrix, perm_p, &signPerm);
     126        gsl_vector *gsl_x_p = gsl_vector_alloc (m);
     127        // solve for the value
     128        gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_b.vector, gsl_x_p);
     129        /*Copy result*/
     130        xMemCpy(outVal,gsl_vector_ptr(gsl_x_p,0),m);
     131        gsl_vector_free(gsl_x_p);
     132        // solve for the derivatives acc. to A * dx = r  with r=db - dA * x
     133        double* r=xNew<double>(m);
     134        gsl_vector *gsl_dx_p = gsl_vector_alloc(m);
     135        for (int dir=0;dir<directionCount;++dir) {
     136                // compute the RHS
     137                for (int i=0; i<m; i++) {
     138                        r[i]=inDeriv[m*m+i][dir]; // this is db[i]
     139                        for (int j=0;j<m; j++) {
     140                                r[i]-=inDeriv[i*m+j][dir]*outVal[j]; // this is dA[i][j]*x[j]
     141                        }
     142                }
     143                gsl_vector_view gsl_r=gsl_vector_view_array(r,m);
     144                gsl_linalg_LU_solve (&gsl_A.matrix, perm_p, &gsl_r.vector, gsl_dx_p);
     145                // reuse r
     146                xMemCpy(r,gsl_vector_ptr(gsl_dx_p,0),m);
     147                for (int i=0; i<m; i++) {
     148                        outDeriv[i][dir]=r[i];
     149                }
     150        }
     151        gsl_vector_free(gsl_dx_p);
     152        xDelete(r);
     153        gsl_permutation_free(perm_p);
     154        xDelete(Acopy);
     155#endif
     156        return 0;
     157}
     158/*}}}*/
     159int EDF_fos_reverse_for_solverx(int m, double *dp_U, int n, double *dp_Z, double* dp_x, double* dp_y) { /*{{{*/
     160        // copy to transpose the matrix
     161        double* transposed=xNew<double>(m*m);
     162        for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) transposed[j*m+i]=dp_x[i*m+j];
     163        gsl_matrix_view aTransposed = gsl_matrix_view_array (transposed,m,m);
     164        // the adjoint of the solution is our right-hand side
     165        gsl_vector_view x_bar=gsl_vector_view_array(dp_U,m);
     166        // the last m elements of dp_Z representing the adjoint of the right-hand side we want to compute:
     167        gsl_vector_view b_bar=gsl_vector_view_array(dp_Z+m*m,m);
     168        gsl_permutation *perm_p = gsl_permutation_alloc (m);
     169        int permSign;
     170        gsl_linalg_LU_decomp (&aTransposed.matrix, perm_p, &permSign);
     171        gsl_linalg_LU_solve (&aTransposed.matrix, perm_p, &x_bar.vector, &b_bar.vector);
     172        // now do the adjoint of the matrix
     173        for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) dp_Z[i*m+j]-=dp_Z[m*m+i]*dp_y[j];
     174        gsl_permutation_free(perm_p);
     175        xDelete(transposed);
     176        return 0;
     177}
     178/*}}}*/
     179int EDF_fov_reverse_for_solverx(int m, int p, double **dpp_U, int n, double **dpp_Z, double* dp_x, double* dp_y) { /*{{{*/
     180        // copy to transpose the matrix
     181        double* transposed=xNew<double>(m*m);
     182        for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) transposed[j*m+i]=dp_x[i*m+j];
     183        gsl_matrix_view aTransposed = gsl_matrix_view_array (transposed,m,m);
     184        gsl_permutation *perm_p = gsl_permutation_alloc (m);
     185        int permSign;
     186        gsl_linalg_LU_decomp (&aTransposed.matrix, perm_p, &permSign);
     187        for (int weightsRowIndex=0;weightsRowIndex<p;++weightsRowIndex) {
     188                // the adjoint of the solution is our right-hand side
     189                gsl_vector_view x_bar=gsl_vector_view_array(dpp_U[weightsRowIndex],m);
     190                // the last m elements of dp_Z representing the adjoint of the right-hand side we want to compute:
     191                gsl_vector_view b_bar=gsl_vector_view_array(dpp_Z[weightsRowIndex]+m*m,m);
     192                gsl_linalg_LU_solve (&aTransposed.matrix, perm_p, &x_bar.vector, &b_bar.vector);
     193                // now do the adjoint of the matrix
     194                for (int i=0; i<m; ++i) for (int j=0; j<m; ++j) dpp_Z[weightsRowIndex][i*m+j]-=dpp_Z[weightsRowIndex][m*m+i]*dp_y[j];
     195        }
     196        gsl_permutation_free(perm_p);
     197        xDelete(transposed);
     198        return 0;
    159199}
    160200/*}}}*/
    161201void SolverxSeq(IssmDouble *X,IssmDouble *A,IssmDouble *B,int n, Parameters* parameters){/*{{{*/
    162202        // pack inputs to conform to the EDF-prescribed interface
     203        // ensure a contiguous block of locations:
     204        ensureContiguousLocations(n*(n+1));
    163205        IssmDouble*  adoubleEDFin=xNew<IssmDouble>(n*(n+1));  // packed inputs, i.e. matrix and right hand side
    164206        for(int i=0; i<n*n;i++)adoubleEDFin[i]    =A[i];      // pack matrix
     
    170212                     n*(n+1), pdoubleEDFin, adoubleEDFin,
    171213                     n, pdoubleEDFout,X);
     214        // for(int i=0; i<n;  i++) {ADOLC_DUMP_MACRO(X[i]);}
    172215        xDelete(adoubleEDFin);
    173216        xDelete(pdoubleEDFin);
     
    181224        int              s;
    182225        gsl_matrix_view  a;
    183         gsl_vector_view  b;
    184         gsl_vector      *x = NULL;
     226        gsl_vector_view  b,x;
    185227        gsl_permutation *p = NULL;
     228//      for (int i=0; i<n*n; ++i) std::cout << "SolverxSeq A["<< i << "]=" << A[i] << std::endl;
     229//      for (int i=0; i<n; ++i) std::cout << "SolverxSeq b["<< i << "]=" << B[i] << std::endl;
    186230        /*A will be modified by LU decomposition. Use copy*/
    187231        double* Acopy = xNew<double>(n*n);
     
    191235        a = gsl_matrix_view_array (Acopy,n,n);
    192236        b = gsl_vector_view_array (B,n);
    193         x = gsl_vector_alloc (n);
     237        x = gsl_vector_view_array (X,n);
    194238
    195239        /*Run LU and solve: */
    196240        p = gsl_permutation_alloc (n);
    197241        gsl_linalg_LU_decomp (&a.matrix, p, &s);
    198         gsl_linalg_LU_solve (&a.matrix, p, &b.vector, x);
    199 
    200         //printf ("x = \n");
    201         //gsl_vector_fprintf (stdout, x, "%g");
    202 
    203         /*Copy result*/
    204         xMemCpy(X,gsl_vector_ptr(x,0),n);
     242        gsl_linalg_LU_solve (&a.matrix, p, &b.vector, &x.vector);
    205243
    206244        /*Clean up and assign output pointer*/
    207245        xDelete(Acopy);
    208246        gsl_permutation_free(p);
    209         gsl_vector_free(x);
    210 #endif
    211 }
    212 /*}}}*/
     247#endif
     248}
     249/*}}}*/
  • issm/trunk/src/c/modules/SpcNodesx/SpcNodesx.cpp

    r9298 r13975  
    1313
    1414        for(int i=0;i<constraints->Size();i++){
    15        
     15
    1616                Constraint* constraint=(Constraint*)constraints->GetObjectByOffset(i);
    1717
  • issm/trunk/src/c/modules/StringToEnumx/StringToEnumx.cpp

    r13395 r13975  
    1919   if(stage==1){
    2020              if (strcmp(name,"AutodiffIsautodiff")==0) return AutodiffIsautodiffEnum;
    21               else if (strcmp(name,"AutodiffDependents")==0) return AutodiffDependentsEnum;
    2221              else if (strcmp(name,"AutodiffNumDependents")==0) return AutodiffNumDependentsEnum;
    23               else if (strcmp(name,"AutodiffIndependents")==0) return AutodiffIndependentsEnum;
     22              else if (strcmp(name,"AutodiffNumDependentObjects")==0) return AutodiffNumDependentObjectsEnum;
     23              else if (strcmp(name,"AutodiffDependentObjectNames")==0) return AutodiffDependentObjectNamesEnum;
     24              else if (strcmp(name,"AutodiffDependentObjectTypes")==0) return AutodiffDependentObjectTypesEnum;
     25              else if (strcmp(name,"AutodiffDependentObjectIndices")==0) return AutodiffDependentObjectIndicesEnum;
     26              else if (strcmp(name,"AutodiffDependentObjects")==0) return AutodiffDependentObjectsEnum;
    2427              else if (strcmp(name,"AutodiffNumIndependents")==0) return AutodiffNumIndependentsEnum;
     28              else if (strcmp(name,"AutodiffNumIndependentObjects")==0) return AutodiffNumIndependentObjectsEnum;
     29              else if (strcmp(name,"AutodiffIndependentObjectNames")==0) return AutodiffIndependentObjectNamesEnum;
     30              else if (strcmp(name,"AutodiffIndependentObjectTypes")==0) return AutodiffIndependentObjectTypesEnum;
     31              else if (strcmp(name,"AutodiffIndependentObjects")==0) return AutodiffIndependentObjectsEnum;
    2532              else if (strcmp(name,"AutodiffJacobian")==0) return AutodiffJacobianEnum;
    2633              else if (strcmp(name,"AutodiffXp")==0) return AutodiffXpEnum;
    27               else if (strcmp(name,"AutodiffFosForwardOutput")==0) return AutodiffFosForwardOutputEnum;
     34              else if (strcmp(name,"AutodiffDriver")==0) return AutodiffDriverEnum;
     35              else if (strcmp(name,"AutodiffFosForwardIndex")==0) return AutodiffFosForwardIndexEnum;
     36              else if (strcmp(name,"AutodiffFovForwardIndices")==0) return AutodiffFovForwardIndicesEnum;
     37              else if (strcmp(name,"AutodiffFosReverseIndex")==0) return AutodiffFosReverseIndexEnum;
     38              else if (strcmp(name,"AutodiffMassFluxSegmentsPresent")==0) return AutodiffMassFluxSegmentsPresentEnum;
     39              else if (strcmp(name,"AutodiffKeep")==0) return AutodiffKeepEnum;
    2840              else if (strcmp(name,"BalancethicknessSpcthickness")==0) return BalancethicknessSpcthicknessEnum;
    2941              else if (strcmp(name,"BalancethicknessStabilization")==0) return BalancethicknessStabilizationEnum;
     
    3749              else if (strcmp(name,"ConstantsReferencetemperature")==0) return ConstantsReferencetemperatureEnum;
    3850              else if (strcmp(name,"ConstantsYts")==0) return ConstantsYtsEnum;
     51              else if (strcmp(name,"DependentObject")==0) return DependentObjectEnum;
    3952              else if (strcmp(name,"DiagnosticAbstol")==0) return DiagnosticAbstolEnum;
    4053              else if (strcmp(name,"DiagnosticIcefront")==0) return DiagnosticIcefrontEnum;
     
    7689              else if (strcmp(name,"HydrologySpcwatercolumn")==0) return HydrologySpcwatercolumnEnum;
    7790              else if (strcmp(name,"HydrologyStabilization")==0) return HydrologyStabilizationEnum;
     91              else if (strcmp(name,"IndependentObject")==0) return IndependentObjectEnum;
    7892              else if (strcmp(name,"InversionControlParameters")==0) return InversionControlParametersEnum;
    7993              else if (strcmp(name,"InversionCostFunction")==0) return InversionCostFunctionEnum;
     
    124138              else if (strcmp(name,"MeshDimension")==0) return MeshDimensionEnum;
    125139              else if (strcmp(name,"MeshEdges")==0) return MeshEdgesEnum;
    126               else if (strcmp(name,"MeshElementconnectivity")==0) return MeshElementconnectivityEnum;
     140         else stage=2;
     141   }
     142   if(stage==2){
     143              if (strcmp(name,"MeshElementconnectivity")==0) return MeshElementconnectivityEnum;
    127144              else if (strcmp(name,"MeshElementonbed")==0) return MeshElementonbedEnum;
    128145              else if (strcmp(name,"MeshElementonsurface")==0) return MeshElementonsurfaceEnum;
     
    138155              else if (strcmp(name,"MeshUpperelements")==0) return MeshUpperelementsEnum;
    139156              else if (strcmp(name,"MeshVertexonbed")==0) return MeshVertexonbedEnum;
    140          else stage=2;
    141    }
    142    if(stage==2){
    143               if (strcmp(name,"MeshVertexonsurface")==0) return MeshVertexonsurfaceEnum;
     157              else if (strcmp(name,"MeshVertexonsurface")==0) return MeshVertexonsurfaceEnum;
    144158              else if (strcmp(name,"MeshX")==0) return MeshXEnum;
    145159              else if (strcmp(name,"MeshY")==0) return MeshYEnum;
     
    152166              else if (strcmp(name,"PrognosticStabilization")==0) return PrognosticStabilizationEnum;
    153167              else if (strcmp(name,"PrognosticVertexPairing")==0) return PrognosticVertexPairingEnum;
     168              else if (strcmp(name,"PrognosticNumRequestedOutputs")==0) return PrognosticNumRequestedOutputsEnum;
     169              else if (strcmp(name,"PrognosticRequestedOutputs")==0) return PrognosticRequestedOutputsEnum;
    154170              else if (strcmp(name,"QmuIsdakota")==0) return QmuIsdakotaEnum;
    155               else if (strcmp(name,"QmuMassFluxSegments")==0) return QmuMassFluxSegmentsEnum;
     171              else if (strcmp(name,"MassFluxSegments")==0) return MassFluxSegmentsEnum;
     172              else if (strcmp(name,"MassFluxSegmentsPresent")==0) return MassFluxSegmentsPresentEnum;
     173              else if (strcmp(name,"QmuMassFluxSegmentsPresent")==0) return QmuMassFluxSegmentsPresentEnum;
    156174              else if (strcmp(name,"QmuNumberofpartitions")==0) return QmuNumberofpartitionsEnum;
    157175              else if (strcmp(name,"QmuNumberofresponses")==0) return QmuNumberofresponsesEnum;
     
    188206              else if (strcmp(name,"SurfaceforcingsMonthlytemperatures")==0) return SurfaceforcingsMonthlytemperaturesEnum;
    189207              else if (strcmp(name,"SurfaceforcingsHc")==0) return SurfaceforcingsHcEnum;
     208              else if (strcmp(name,"SurfaceforcingsHref")==0) return SurfaceforcingsHrefEnum;
     209              else if (strcmp(name,"SurfaceforcingsSmbref")==0) return SurfaceforcingsSmbrefEnum;
    190210              else if (strcmp(name,"SurfaceforcingsSmbPosMax")==0) return SurfaceforcingsSmbPosMaxEnum;
    191211              else if (strcmp(name,"SurfaceforcingsSmbPosMin")==0) return SurfaceforcingsSmbPosMinEnum;
     
    241261              else if (strcmp(name,"PrognosticSolution")==0) return PrognosticSolutionEnum;
    242262              else if (strcmp(name,"SteadystateSolution")==0) return SteadystateSolutionEnum;
    243               else if (strcmp(name,"SurfaceSlopeAnalysis")==0) return SurfaceSlopeAnalysisEnum;
     263         else stage=3;
     264   }
     265   if(stage==3){
     266              if (strcmp(name,"SurfaceSlopeAnalysis")==0) return SurfaceSlopeAnalysisEnum;
    244267              else if (strcmp(name,"SurfaceSlopeSolution")==0) return SurfaceSlopeSolutionEnum;
    245268              else if (strcmp(name,"SurfaceSlopeXAnalysis")==0) return SurfaceSlopeXAnalysisEnum;
     
    261284              else if (strcmp(name,"Loads")==0) return LoadsEnum;
    262285              else if (strcmp(name,"Materials")==0) return MaterialsEnum;
    263          else stage=3;
    264    }
    265    if(stage==3){
    266               if (strcmp(name,"Nodes")==0) return NodesEnum;
     286              else if (strcmp(name,"Nodes")==0) return NodesEnum;
    267287              else if (strcmp(name,"Parameters")==0) return ParametersEnum;
    268288              else if (strcmp(name,"Vertices")==0) return VerticesEnum;
     
    277297              else if (strcmp(name,"DofIndexing")==0) return DofIndexingEnum;
    278298              else if (strcmp(name,"DoubleInput")==0) return DoubleInputEnum;
     299              else if (strcmp(name,"DataSetParam")==0) return DataSetParamEnum;
    279300              else if (strcmp(name,"DoubleMatArrayParam")==0) return DoubleMatArrayParamEnum;
    280301              else if (strcmp(name,"DoubleMatParam")==0) return DoubleMatParamEnum;
     
    306327              else if (strcmp(name,"Penta")==0) return PentaEnum;
    307328              else if (strcmp(name,"PentaP1Input")==0) return PentaP1InputEnum;
     329              else if (strcmp(name,"Profiler")==0) return ProfilerEnum;
    308330              else if (strcmp(name,"MatrixParam")==0) return MatrixParamEnum;
    309331              else if (strcmp(name,"VectorParam")==0) return VectorParamEnum;
     
    362384              else if (strcmp(name,"SurfaceAbsVelMisfit")==0) return SurfaceAbsVelMisfitEnum;
    363385              else if (strcmp(name,"SurfaceArea")==0) return SurfaceAreaEnum;
    364               else if (strcmp(name,"SurfaceAverageVelMisfit")==0) return SurfaceAverageVelMisfitEnum;
     386         else stage=4;
     387   }
     388   if(stage==4){
     389              if (strcmp(name,"SurfaceAverageVelMisfit")==0) return SurfaceAverageVelMisfitEnum;
    365390              else if (strcmp(name,"SurfaceLogVelMisfit")==0) return SurfaceLogVelMisfitEnum;
    366391              else if (strcmp(name,"SurfaceLogVxVyMisfit")==0) return SurfaceLogVxVyMisfitEnum;
     
    384409              else if (strcmp(name,"VyPicard")==0) return VyPicardEnum;
    385410              else if (strcmp(name,"Vz")==0) return VzEnum;
    386          else stage=4;
    387    }
    388    if(stage==4){
    389               if (strcmp(name,"VzMacAyeal")==0) return VzMacAyealEnum;
     411              else if (strcmp(name,"VzMacAyeal")==0) return VzMacAyealEnum;
    390412              else if (strcmp(name,"VzPattyn")==0) return VzPattynEnum;
    391413              else if (strcmp(name,"VzPicard")==0) return VzPicardEnum;
     
    477499              else if (strcmp(name,"OldGradient")==0) return OldGradientEnum;
    478500              else if (strcmp(name,"OutputFilePointer")==0) return OutputFilePointerEnum;
     501              else if (strcmp(name,"OutputFileName")==0) return OutputFileNameEnum;
     502              else if (strcmp(name,"LockFileName")==0) return LockFileNameEnum;
    479503              else if (strcmp(name,"PetscOptionsAnalyses")==0) return PetscOptionsAnalysesEnum;
    480504              else if (strcmp(name,"PetscOptionsStrings")==0) return PetscOptionsStringsEnum;
     
    483507              else if (strcmp(name,"QmuOutName")==0) return QmuOutNameEnum;
    484508              else if (strcmp(name,"Regular")==0) return RegularEnum;
    485               else if (strcmp(name,"Scaled")==0) return ScaledEnum;
     509         else stage=5;
     510   }
     511   if(stage==5){
     512              if (strcmp(name,"Scaled")==0) return ScaledEnum;
    486513              else if (strcmp(name,"Separate")==0) return SeparateEnum;
    487514              else if (strcmp(name,"Sset")==0) return SsetEnum;
     
    501528              else if (strcmp(name,"Paterson")==0) return PatersonEnum;
    502529              else if (strcmp(name,"Arrhenius")==0) return ArrheniusEnum;
    503          else stage=5;
     530         else stage=6;
    504531   }
    505532        /*If we reach this point, the string provided has not been found*/
  • issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp

    r13395 r13975  
    2222        /*Compute Misfit: */
    2323        for (i=0;i<elements->Size();i++){
    24                 element=(Element*)elements->GetObjectByOffset(i);
     24                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2525                J+=element->SurfaceAbsVelMisfit(process_units,weight_index);
    2626        }
     
    2828        /*Sum all J from all cpus of the cluster:*/
    2929        #ifdef _HAVE_MPI_
    30         MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
    31         MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
     30        MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
     31        MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
    3232        J=J_sum;
    3333        #endif
  • issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.cpp

    r12706 r13975  
    1212
    1313void SurfaceAreax( IssmDouble* pS, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters){
    14        
     14
    1515        /*Intermediary*/
    1616        Element* element=NULL;
     
    2020        IssmDouble S=0;
    2121        IssmDouble S_sum;
    22        
     22
    2323        /*Compute gradients: */
    2424        for (i=0;i<elements->Size();i++){
    25                 element=(Element*)elements->GetObjectByOffset(i);
     25                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2626                S+=element->SurfaceArea();
    2727        }
     
    2929        /*Sum all J from all cpus of the cluster:*/
    3030        #ifdef _HAVE_MPI_
    31         MPI_Reduce (&S,&S_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
    32         MPI_Bcast(&S_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
     31        MPI_Reduce (&S,&S_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
     32        MPI_Bcast(&S_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
    3333        S=S_sum;
    3434        #endif
  • issm/trunk/src/c/modules/SurfaceAreax/SurfaceAreax.h

    r13395 r13975  
    1313
    1414#endif  /* _SURFACEAREAX_H */
    15 
  • issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp

    r13395 r13975  
    2626        /*Compute Misfit: */
    2727        for (i=0;i<elements->Size();i++){
    28                 element=(Element*)elements->GetObjectByOffset(i);
     28                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2929                J+=element->SurfaceAverageVelMisfit(process_units,weight_index);
    3030        }
     
    3232        /*Sum all J from all cpus of the cluster:*/
    3333        #ifdef _HAVE_MPI_
    34         MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
    35         MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
     34        MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
     35        MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
    3636        J=J_sum;
    3737        #endif
  • issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp

    r13395 r13975  
    2222        /*Compute Misfit: */
    2323        for (i=0;i<elements->Size();i++){
    24                 element=(Element*)elements->GetObjectByOffset(i);
     24                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2525                J+=element->SurfaceLogVelMisfit(process_units,weight_index);
    2626        }
     
    2828        /*Sum all J from all cpus of the cluster:*/
    2929        #ifdef _HAVE_MPI_
    30         MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
    31         MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
     30        MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
     31        MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
    3232        J=J_sum;
    3333        #endif
  • issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp

    r13395 r13975  
    2222        /*Compute Misfit: */
    2323        for (i=0;i<elements->Size();i++){
    24                 element=(Element*)elements->GetObjectByOffset(i);
     24                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2525                J+=element->SurfaceLogVxVyMisfit(process_units,weight_index);
    2626        }
     
    2828        /*Sum all J from all cpus of the cluster:*/
    2929        #ifdef _HAVE_MPI_
    30         MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
    31         MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
     30        MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
     31        MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
    3232        J=J_sum;
    3333        #endif
  • issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp

    r13395 r13975  
    2222        /*Compute Misfit: */
    2323        for (i=0;i<elements->Size();i++){
    24                 element=(Element*)elements->GetObjectByOffset(i);
     24                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2525                J+=element->SurfaceRelVelMisfit(process_units,weight_index);
    2626        }
     
    2828        /*Sum all J from all cpus of the cluster:*/
    2929        #ifdef _HAVE_MPI_
    30         MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
    31         MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
     30        MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
     31        MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
    3232        J=J_sum;
    3333        #endif
  • issm/trunk/src/c/modules/ThicknessAbsMisfitx/ThicknessAbsMisfitx.cpp

    r13395 r13975  
    2222        /*Compute Misfit: */
    2323        for (i=0;i<elements->Size();i++){
    24                 element=(Element*)elements->GetObjectByOffset(i);
     24                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2525                J+=element->ThicknessAbsMisfit(process_units,weight_index);
    2626        }
     
    2828        /*Sum all J from all cpus of the cluster:*/
    2929        #ifdef _HAVE_MPI_
    30         MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
    31         MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
     30        MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
     31        MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
    3232        J=J_sum;
    3333        #endif
  • issm/trunk/src/c/modules/ThicknessAcrossGradientx/ThicknessAcrossGradientx.cpp

    r13395 r13975  
    2222        /*Compute Misfit: */
    2323        for (i=0;i<elements->Size();i++){
    24                 element=(Element*)elements->GetObjectByOffset(i);
     24                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2525                J+=element->ThicknessAcrossGradient(process_units,weight_index);
    2626        }
     
    2828        /*Sum all J from all cpus of the cluster:*/
    2929        #ifdef _HAVE_MPI_
    30         MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
    31         MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
     30        MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
     31        MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
    3232        J=J_sum;
    3333        #endif
  • issm/trunk/src/c/modules/ThicknessAlongGradientx/ThicknessAlongGradientx.cpp

    r13395 r13975  
    2222        /*Compute Misfit: */
    2323        for (i=0;i<elements->Size();i++){
    24                 element=(Element*)elements->GetObjectByOffset(i);
     24                element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
    2525                J+=element->ThicknessAlongGradient(process_units,weight_index);
    2626        }
     
    2828        /*Sum all J from all cpus of the cluster:*/
    2929        #ifdef _HAVE_MPI_
    30         MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD );
    31         MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,MPI_COMM_WORLD);
     30        MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
     31        MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
    3232        J=J_sum;
    3333        #endif
  • issm/trunk/src/c/modules/TriMeshx/TriMeshx.cpp

    r13395 r13975  
    1111#include "../../EnumDefinitions/EnumDefinitions.h"
    1212/*ANSI_DECLARATORS needed to call triangle library: */
    13 #ifndef ANSI_DECLARATORS
    14 #define ANSI_DECLARATORS
    15 #include "triangle.h"
    16 #undef ANSI_DECLARATORS
    17 #else
    18 #include "triangle.h"
     13#if defined(_HAVE_TRIANGLE_)
     14        #ifndef ANSI_DECLARATORS
     15        #define ANSI_DECLARATORS
     16        #include "triangle.h"
     17        #undef ANSI_DECLARATORS
     18        #else
     19        #include "triangle.h"
     20        #endif
    1921#endif
    2022/*}}}*/
     
    2224void TriMeshx(SeqMat<IssmPDouble>** pindex,SeqVec<IssmPDouble>** px,SeqVec<IssmPDouble>** py,SeqMat<IssmPDouble>** psegments,SeqVec<IssmPDouble>** psegmentmarkerlist,DataSet* domain,DataSet* rifts,double area){
    2325
     26#if !defined(_HAVE_TRIANGLE_)
     27        _error_("triangle has not been installed");
     28#else
    2429        /*indexing: */
    2530        int i,j;
     
    7681                }
    7782        }
    78        
     83
    7984        /*fill in the point attribute list: */
    8085        in.pointattributelist = xNew<REAL>(in.numberofpoints*in.numberofpointattributes);
    8186        for (i=0;i<in.numberofpoints;i++) in.pointattributelist[i] = 0.0;
    82        
     87
    8388        /*fill in the point marker list: */
    8489        in.pointmarkerlist = xNew<int>(in.numberofpoints);
     
    96101                in.numberofsegments+=contour->nods-1;
    97102        }
    98        
     103
    99104        in.segmentlist = xNew<int>(in.numberofsegments*2);
    100105        in.segmentmarkerlist = xNewZeroInit<int>(in.numberofsegments);
     
    128133                counter++;
    129134        }
    130        
     135
    131136        /*Build regions: */
    132137        in.numberofregions = 0;
     
    194199        index_matrix=new SeqMat<IssmPDouble>(index,out.numberoftriangles,3,1.0);
    195200        *pindex=index_matrix;
    196        
     201
    197202        segments_matrix=new SeqMat<IssmPDouble>(segments,out.numberofsegments,3,1.0);
    198203        *psegments=segments_matrix;
     
    201206        *py=new SeqVec<IssmPDouble>(y,out.numberofpoints);
    202207        *psegmentmarkerlist=new SeqVec<IssmPDouble>(segmentmarkerlist,out.numberofsegments);
     208#endif
    203209}
  • issm/trunk/src/c/modules/TriMeshx/TriMeshx.h

    r13395 r13975  
    66#define _TRIMESHX_H_
    77
    8 #include "string.h"
     8#include <string.h>
    99#include "../../Container/Container.h"
    1010#include "../../classes/objects/objects.h"
  • issm/trunk/src/c/modules/TriaSearchx/TriaSearchx.cpp

    r13395 r13975  
    2424        R2     r;
    2525        I2     I;
    26         int    i,j,k;
    27         int    i0,i1,i2;
    28         double areacoord[3];
    29         double aa,bb;
    30         double data_value;
     26        int    i;
    3127        Icoor2 dete[3];
    32         int verbose=0;
    3328
    34         // read background mesh
     29        /* read background mesh */
    3530        Mesh Th(index,x,y,nods,nel);
    3631        Th.CreateSingleVertexToTriangleConnectivity();
     
    4035                //Get current point coordinates
    4136                r.x=x0[i]; r.y=y0[i];
    42                
     37
    4338                I=Th.R2ToI2(r);
    4439
  • issm/trunk/src/c/modules/UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.cpp

    r13395 r13975  
    1111
    1212void UpdateDynamicConstraintsx(Constraints* constraints,Nodes* nodes,Parameters* parameters,Vector<IssmDouble>* yg){
    13        
     13
    1414        int configuration_type;
    1515        IssmDouble* yg_serial=NULL;
  • issm/trunk/src/c/modules/VecMergex/VecMergex.cpp

    r13395 r13975  
    1818        /*retrieve parameters: */
    1919        parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
    20        
     20
    2121        /*serialize uf: */
    2222        uf_serial=uf->ToMPISerial();
    23 
    2423
    2524        /*Do we have any nodes for this configuration? :*/
  • issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.cpp

    r6232 r13975  
    1111void VerticesDofx( Vertices* vertices, Parameters* parameters) {
    1212
    13         int i;
    14 
    15         int  found=0;
    16         extern int num_procs;
    17         extern int my_rank;
    18        
    1913        /*intermediary: */
    2014        int  numberofvertices;
     
    2317        numberofvertices=vertices->NumberOfVertices();
    2418
    25         /*Ensure that only for each cpu, the partition border vertices only will be taken into account once
    26          * across the cluster. To do so, we flag all the clone vertices: */
     19        /*Ensure that only for each cpu, the partition border vertices only will be
     20         * taken into account once across the cluster. To do so, we flag all the
     21         * clone vertices: */
    2722        vertices->FlagClones(numberofvertices);
    2823
    29         /*Go through all vertices and distribute 1 dof at a time. When a  vertex has already been distributed his dof on a cpu,
    30          * all other cpus with the same vertex cannot distribute it anymore. Use clone field to be sure of that: */
    31         vertices->DistributeDofs(numberofvertices,1); //only 1 dof per vertex.
     24        /*Go through all vertices and distribute pids*/
     25        vertices->DistributePids(numberofvertices);
    3226
    3327}
  • issm/trunk/src/c/modules/VerticesDofx/VerticesDofx.h

    r13395 r13975  
    1313
    1414#endif  /* _VERTICESDOFX_H */
    15 
  • issm/trunk/src/c/modules/modules.h

    r13395 r13975  
    77
    88/*Modules: */
    9 #include "./AddExternalResultx/AddExternalResultx.h"
    10 #include "./AutodiffDriversx/AutodiffDriversx.h"
    119#include "./AverageFilterx/AverageFilterx.h"
    1210#include "./AverageOntoPartitionx/AverageOntoPartitionx.h"
     
    2321#include "./ControlInputSetGradientx/ControlInputSetGradientx.h"
    2422#include "./ControlInputScaleGradientx/ControlInputScaleGradientx.h"
    25 #include "./CostFunctionx/CostFunctionx.h"
    2623#include "./CreateNodalConstraintsx/CreateNodalConstraintsx.h"
    27 #include "./DakotaResponsesx/DakotaResponsesx.h"
    2824#include "./Delta18oParameterizationx/Delta18oParameterizationx.h"
    2925#include "./DragCoefficientAbsGradientx/DragCoefficientAbsGradientx.h"
     
    3834#include "./GroundinglineMigrationx/GroundinglineMigrationx.h"
    3935#include "./HoleFillerx/HoleFillerx.h"
    40 #include "./TotalSmbx/TotalSmbx.h"
    41 #include "./IceVolumex/IceVolumex.h"
    4236#include "./InputControlUpdatex/InputControlUpdatex.h"
    4337#include "./InputConvergencex/InputConvergencex.h"
     
    6761#include "./Krigingx/Krigingx.h"
    6862#include "./Shp2Kmlx/Shp2Kmlx.h"
    69 #include "./MassFluxx/MassFluxx.h"
    70 #include "./MaxAbsVxx/MaxAbsVxx.h"
    71 #include "./MaxAbsVyx/MaxAbsVyx.h"
    72 #include "./MaxAbsVzx/MaxAbsVzx.h"
    73 #include "./MaxVelx/MaxVelx.h"
    74 #include "./ElementResponsex/ElementResponsex.h"
    75 #include "./MaxVxx/MaxVxx.h"
    76 #include "./MaxVyx/MaxVyx.h"
    77 #include "./MaxVzx/MaxVzx.h"
    7863#include "./Mergesolutionfromftogx/Mergesolutionfromftogx.h"
    7964#include "./MeshPartitionx/MeshPartitionx.h"
    8065#include "./MeshProfileIntersectionx/MeshProfileIntersectionx.h"
    81 #include "./MinVelx/MinVelx.h"
    82 #include "./MinVxx/MinVxx.h"
    83 #include "./MinVyx/MinVyx.h"
    84 #include "./MinVzx/MinVzx.h"
    8566#include "./SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.h"
    8667#include "./SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.h"
     
    9980#include "./PositiveDegreeDayx/PositiveDegreeDayx.h"
    10081#include "./PropagateFlagsFromConnectivityx/PropagateFlagsFromConnectivityx.h"
    101 #include "./Dakotax/Dakotax.h"
    10282#include "./Reduceloadx/Reduceloadx.h"
    10383#include "./Reducevectorgtosx/Reducevectorgtosx.h"
    10484#include "./Reducevectorgtofx/Reducevectorgtofx.h"
    105 #include "./RequestedOutputsx/RequestedOutputsx.h"
    106 #include "./RequestedDependentsx/RequestedDependentsx.h"
    10785#include "./ResetConstraintsx/ResetConstraintsx.h"
    10886#include "./ResetCoordinateSystemx/ResetCoordinateSystemx.h"
    109 #include "./Responsex/Responsex.h"
    11087#include "./RheologyBbarAbsGradientx/RheologyBbarAbsGradientx.h"
    11188#include "./Scotchx/Scotchx.h"
     
    11491#include "./SpcNodesx/SpcNodesx.h"
    11592#include "./SurfaceAreax/SurfaceAreax.h"
    116 #include "./SystemMatricesx/SystemMatricesx.h"
    117 #include "./CreateJacobianMatrixx/CreateJacobianMatrixx.h"
    118 #include "./TimeAdaptx/TimeAdaptx.h"
    11993#include "./TriaSearchx/TriaSearchx.h"
    12094#include "./TriMeshx/TriMeshx.h"
     95#include "./TriMeshProcessRiftsx/TriMeshProcessRiftsx.h"
    12196#include "./ThicknessAbsMisfitx/ThicknessAbsMisfitx.h"
    122 #include "./ThicknessAbsGradientx/ThicknessAbsGradientx.h"
    12397#include "./ThicknessAlongGradientx/ThicknessAlongGradientx.h"
    12498#include "./ThicknessAcrossGradientx/ThicknessAcrossGradientx.h"
    125 #include "./UpdateVertexPositionsx/UpdateVertexPositionsx.h"
    126 #include "./UpdateConstraintsx/UpdateConstraintsx.h"
    12799#include "./UpdateDynamicConstraintsx/UpdateDynamicConstraintsx.h"
    128100#include "./VerticesDofx/VerticesDofx.h"
  • issm/trunk/src/c/shared/Alloc/alloc.cpp

    r13395 r13975  
    1111 * the allocation routines described here do not work.
    1212 */
    13 
    1413
    1514#ifdef HAVE_CONFIG_H
     
    2827
    2928void xdelete(Matrix<IssmDouble>** pv){
    30        
     29
    3130        if (pv && *pv){
    3231                /*There is no mxDelete in the Matlab API -> using delete trips up Matlab. So we
  • issm/trunk/src/c/shared/Alloc/xNewDelete.h

    r13395 r13975  
    88#include <cassert>
    99
    10 
    1110// memory management of types
    1211// T with non-trivial constructors require
    1312// C++ style memory management
    1413#define USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
    15 // but for speed on may alternatively use C memory managment
     14// but for speed on may alternatively use C memory management
    1615// but can do so safely only for T that are at most
    1716// plain old data structures (POD)
     
    6968  assert(aT_p);
    7069  return aT_p;
     70#endif
     71}
     72
     73template <class T>
     74T** xNewZeroInit(unsigned int dim1, unsigned int dim2) {
     75#ifdef USE_CXX_MEMORY_MANAGMENT_FOR_NON_POD_TYPES
     76  T** aT_pp=xNew<T>(dim1,dim2);
     77  for (unsigned int i=0; i<dim1*dim2;++i)
     78    (*aT_pp)[i]=(T)0;
     79  return aT_pp;
     80#else
     81  T* buf=(T*)calloc(dim1*dim2*sizeof(T));
     82  assert(buf );
     83  T** aT_pp =(T**)malloc(dim1*sizeof(T*));
     84  assert(aT_pp );
     85  for (unsigned int i=0;i<dim1;++i) {
     86    aT_pp [i]=buf;
     87    buf+=dim2;
     88  }
     89  return aT_pp ;
    7190#endif
    7291}
     
    134153
    135154#endif
    136 
  • issm/trunk/src/c/shared/Bamg/shared.h

    r3913 r13975  
    22 * \brief: header file for all shared  routines.
    33 */
    4 
    54
    65#ifndef _SHAREDBamg_H_
  • issm/trunk/src/c/shared/Elements/GetGlobalDofList.cpp

    r12706 r13975  
    99        int* ndof_list=NULL;
    1010        int *doflist = NULL;
    11 
    1211
    1312        if(numnodes){
  • issm/trunk/src/c/shared/Elements/GetLocalDofList.cpp

    r12706 r13975  
    1515                ndof_list=xNew<int>(numnodes);
    1616                ngdof_list_cumulative=xNew<int>(numnodes);
    17 
    1817
    1918                /*Get number of dofs per node, and total for this given set*/
  • issm/trunk/src/c/shared/Elements/Paterson.cpp

    r12706 r13975  
    1010
    1111IssmDouble Paterson(IssmDouble temperature){
    12        
     12
    1313        /*output: */
    1414        IssmDouble B;
     
    2929//      % fittedmodel=fit(Temp,B,'cubicspline');
    3030//      % B=fittedmodel(temperature);
    31 
    3231
    3332        if(T<=-45.0){
     
    6160                B=pow((IssmPDouble)10,(IssmPDouble)8)*(-0.003748937622487*pow(T+5,3)+0.015290593619213*pow(T+5,2)  -0.048160403003748*(T+5)+  0.854987973338348);
    6261        }
    63         else if(T>=-2.0){
     62        else{
    6463                B=pow((IssmPDouble)10,(IssmPDouble)8)*(-0.003748937622488*pow(T+2,3)-0.018449844983174*pow(T+2,2)  -0.057638157095631*(T+2)+  0.746900791092860);
    6564        }
     
    7069        return B;
    7170}
    72 
    73 
    74 
  • issm/trunk/src/c/shared/Elements/PddSurfaceMassBalance.cpp

    r13395 r13975  
    1010  IssmDouble B;    // surface mass balance, melt+accumulation
    1111
    12   int    iqj,imonth, j;
    13  
     12  int    iqj,imonth;
     13
    1414  IssmDouble saccu;     // yearly surface accumulation
    1515  IssmDouble smelt;     // yearly melt
     
    1919  IssmDouble runoff; //meltwater only, does not include rain
    2020  IssmDouble sconv; //rhow_rain/rhoi / 12 months
    21  
    22   IssmDouble density;
     21
    2322  IssmDouble lapser=6.5/1000., sealev=0.;    // lapse rate. degrees per meter. 7.5 lev's 99 paper, 9 Marshall 99 paper
    2423  IssmDouble desfac = 0.5;                 // desert elevation factor
     
    2726  IssmDouble st;             // elevation between altitude of the temp record and current altitude
    2827  IssmDouble sp;             // elevation between altitude of the prec record and current altitude
    29  
     28
    3029  // PDD and PD constants and variables
    3130  IssmDouble siglim;          // sigma limit for the integration which is equal to 2.5 sigmanorm
     
    3534  IssmDouble DT = 0.02;
    3635  IssmDouble pddt, pd; // pd: snow/precip fraction, precipitation falling as snow
    37  
     36
    3837  IssmDouble q, qmpt; // q is desert/elev. fact, hnpfac is huybrect fact, and pd is normal dist.
    3938  IssmDouble qm = 0.;        // snow part of the precipitation
     
    4241  IssmDouble pdd = 0.;     
    4342  IssmDouble frzndd = 0.; 
    44  
     43
    4544  IssmDouble tstar;          // monthly mean surface temp
    4645  IssmDouble Tsum= 0.;       // average summer (JJA) temperature
    4746  IssmDouble Tsurf = 0.;     // average annual temperature   
    48  
    4947
    5048  IssmDouble deltm=1./12.;
    5149  int    ismon[12]={11,0,1,2,3,4,5,6,7,8,9,10};
    52  
     50
    5351  IssmDouble snwm;  // snow that could have been melted in a year.
    5452  IssmDouble snwmf; //  ablation factor for snow per positive degree day.
    5553  IssmDouble smf;   //  ablation factor for ice per pdd (Braithwaite 1995 from tarasov 2002).
    56  
     54
    5755  IssmDouble dfrz=1.5, CovrLm=2009./3.35e+5, dCovrLm=dfrz*CovrLm; //m*J kg^-1 C^-1 /(J kg^-1)=m/C yr
    5856  IssmDouble supice,supcap,diffndd;
    5957  IssmDouble fsupT=0.5,  fsupndd=0.5;  // Tsurf mode factors for supice
    6058  IssmDouble pddtj, hmx2;
    61  
     59
    6260  sconv=(rho_water/rho_ice)/12.; //rhow_rain/rhoi / 12 months
    6361
     
    6866  siglim0c = siglimc/DT + 0.5;
    6967  PDup = siglimc+PDCUT;
    70  
     68
    7169  // seasonal loop
    7270    for (iqj = 0; iqj < 12; iqj++){
    7371      imonth =  ismon[iqj];
    74  
     72
    7573      st=(s-s0t)/1000.;
    7674      tstar = monthlytemperatures[imonth] - lapser *max(st,sealev);
    7775      Tsurf = tstar*deltm+Tsurf;       
    78      
     76
    7977      /*********compute PD ****************/
    8078      if (tstar < PDup){
     
    8381      else {
    8482        pd = 0.;}
    85      
     83
    8684      /******exp des/elev precip reduction*******/
    8785      sp=(s-s0p)/1000.; // deselev effect is wrt chng in topo
    8886      if (sp>0.0){q = exp(-desfac*sp);}
    8987      else {q = 1.0;}
    90      
     88
    9189      qmt= qmt + monthlyprec[imonth]*sconv;  //*sconv to convert in m of ice equivalent per month
    9290      qmpt= q*monthlyprec[imonth]*sconv;           
    9391      qmp= qmp + qmpt;
    9492      qm= qm + qmpt*pd;
    95      
     93
    9694      /*********compute PDD************/
    9795      // ndd(month)=-(tstar-pdd(month)) since ndd+pdd gives expectation of
     
    105103      else{frzndd = frzndd - tstar*deltm; }
    106104  } // end of seasonal loop
    107  
     105
    108106  //******************************************************************
    109107    saccu = qm;
    110108    prect = qmp;     // total precipitation during 1 year taking into account des. ef.
    111109    Tsum=Tsum/3;
    112    
     110
    113111    /***** determine PDD factors *****/
    114112    if(Tsum< -1.) {
     
    126124    snwmf=0.95*snwmf;
    127125    smf=0.95*smf;
    128    
     126
    129127    /*****  compute PDD ablation and refreezing *****/
    130128    pddt = pdd *365;
    131129    snwm = snwmf*pddt;       // snow that could have been melted in a year
    132130    hmx2 = min(h,dfrz);   // refreeze active layer max depth: dfrz
    133    
     131
    134132    if(snwm < saccu) {
    135133      water=prect-saccu + snwm; //water=rain + snowmelt
     
    147145      //     hold the meltwater around for refreezing? And melt-time will have
    148146      //     low seasonal frzndd
    149      
     147
    150148      //      Superimposed ice :  Pfeffer et al. 1991, Tarasov 2002
    151      
     149
    152150      supice= min(hmx2*CovrLm*frzndd+2.2*(saccu-snwm), water); // superimposed ice
    153151      supcap=min(2.2*(saccu-snwm),water);
     
    172170    //     does supice make sense when H< 0.1m? then d=thermoactive ice layer ////
    173171    //     < 0.1
    174    
     172
    175173    //     make more sense to just use residual pdd-ndd except that pdd
    176174    //     residual not clear yet
     
    197195    if(Tsurf<0) {
    198196      Tsurf= min(Tsurf+fsupT*diffndd , 0.);}
    199    
     197
    200198    B = -smelt+saccu;
    201199    B = B/yts;
    202200    pddtj=pddt;
    203  
     201
    204202  return B;
    205203}
  • issm/trunk/src/c/shared/Elements/PrintArrays.cpp

    r13395 r13975  
    1010                for(int j=0;j<cols;j++) _printString_( " " << setw(11) << setprecision (5) << array[i*cols+j]);
    1111                _printLine_(" ]");
     12        } 
     13        _printLine_("");
     14}
     15void printsparsity(IssmPDouble* array,int lines,int cols){
     16        int count;
     17        _printLine_("");
     18        for(int i=0;i<lines;i++){ 
     19                _printString_("   [ ");
     20                count = 0;
     21                for(int j=0;j<cols;j++){
     22                        if(array[i*cols+j]!=0.0){
     23                                _printString_( " X"); count++;
     24                        }
     25                        else
     26                         _printString_( " .");
     27                }
     28                _printLine_(" ] "<<i<<" => "<<count);
    1229        } 
    1330        _printLine_("");
  • issm/trunk/src/c/shared/Elements/TransformLoadVectorCoord.cpp

    r13395 r13975  
    2020void TransformLoadVectorCoord(ElementVector* pe,Node** nodes,int numnodes,int* cs_array){
    2121
    22         int     i,j;
     22        int     i;
    2323        int     numdofs   = 0;
    2424        IssmDouble *transform = NULL;
  • issm/trunk/src/c/shared/Elements/TransformSolutionCoord.cpp

    r13395 r13975  
    2121void TransformSolutionCoord(IssmDouble* solution,Node** nodes,int numnodes,int* cs_array){
    2222
    23         int     i,j;
     23        int     i;
    2424        int     numdofs   = 0;
    2525        IssmDouble *transform = NULL;
  • issm/trunk/src/c/shared/Elements/elements.h

    r13395 r13975  
    4040void printarray(IssmPDouble* array,int lines,int cols=1);
    4141void printarray(int* array,int lines,int cols=1);
     42void printsparsity(IssmPDouble* array,int lines,int cols=1);
    4243void printbinary(int n);
    4344#endif //ifndef _SHARED_ELEMENTS_H_
  • issm/trunk/src/c/shared/Exceptions/Exceptions.cpp

    r13395 r13975  
    1212#include "../../include/include.h"
    1313
    14 ErrorException::ErrorException(const string &what_arg){
     14ErrorException::ErrorException(const string &what_arg){/*{{{*/
    1515
    1616        what_str=what_arg;
     
    1818        function_name="";
    1919        file_line=0;
    20 }
    21 
    22 ErrorException::ErrorException(const string& what_file, const string& what_function,int what_line, const string& what_arg){
     20}/*}}}*/
     21ErrorException::ErrorException(const string& what_file, const string& what_function,int what_line, const string& what_arg){/*{{{*/
    2322
    2423        what_str=what_arg;
     
    2625        function_name=what_function;
    2726        file_line=what_line;
    28 }
     27}/*}}}*/
     28ErrorException::~ErrorException() throw(){/*{{{*/
     29}/*}}}*/
     30const char* ErrorException::what() const throw(){/*{{{*/
     31        return what_str.c_str();
     32}/*}}}*/
     33void ErrorException::Report() const{/*{{{*/
    2934
    30 ErrorException::~ErrorException() throw(){
    31         extern int num_procs;
    32         /*We want the report only for matlab modules, otherwise we get twice the report
    33          * We assume that if num_procs==1, it is a module (FIXME)*/
    34         if(num_procs==1) this->Report();
    35 }
     35        int my_rank;
     36        int num_procs;
    3637
    37 const char* ErrorException::what() const throw(){
    38         return what_str.c_str();
    39 }
    40 
    41 void ErrorException::Report() const{
    42         extern int my_rank;
    43         extern int num_procs;
     38        /*recover my_rank and num_procs:*/
     39        my_rank=IssmComm::GetRank();
     40        num_procs=IssmComm::GetSize();
    4441
    4542        if (function_name=="" || file_line==0){ //WINDOWS
     
    4845        else{
    4946                if(num_procs==1){
    50                         _printLine_("\n??? Error using ==> " << file_name.c_str() << ":" << file_line);
     47                        _printLine_("\n??? Error in ==> " << file_name.c_str() << ":" << file_line);
    5148                        _printLine_(function_name.c_str() << " error message: " << what() << "\n");
    5249                }
    5350                else{
    54                         _printLine_("\n[" << my_rank << "] ??? Error using ==> " << file_name.c_str() << ":" << file_line);
    55                         _printLine_("[" << my_rank << "] " << function_name.c_str() << " error message: " << what() << "\n");
     51                        _printLine_("\n[" << my_rank<< "] ??? Error using ==> " << file_name.c_str() << ":" << file_line);
     52                        _printLine_(  "[" << my_rank << "] " << function_name.c_str() << " error message: " << what() << "\n");
    5653                }
    5754        }
    5855        return;
    59 }
     56}/*}}}*/
     57const char* ErrorException::MatlabReport() const{/*{{{*/
     58
     59        /*Output*/
     60        std::ostringstream buffer;
     61
     62        if (this->file_line==0){ //WINDOWS
     63                 buffer << " error message: " << (this->what_str).c_str();
     64        }
     65        else{
     66                buffer << "\nError in ==> " << (this->file_name).c_str() << ":" << file_line << "\n";
     67                buffer << (this->function_name).c_str() << " error message: " << (this->what_str).c_str();
     68        }
     69
     70        const string buffer2 = buffer.str();
     71        return buffer2.c_str();
     72}/*}}}*/
     73const char* ErrorException::PythonReport() const{/*{{{*/
     74
     75        /*Output*/
     76        std::ostringstream buffer;
     77
     78        if (this->file_line==0){ //WINDOWS
     79                buffer << " error message: " << (this->what_str).c_str();
     80        }
     81        else{
     82                buffer << "\nError in ==> " << (this->file_name).c_str() << ":" << file_line << "\n";
     83                buffer << (this->function_name).c_str() << " error message: " << (this->what_str).c_str();
     84        }
     85
     86        const string buffer2 = buffer.str();
     87        return buffer2.c_str();
     88}/*}}}*/
  • issm/trunk/src/c/shared/Exceptions/exceptions.h

    r13395 r13975  
    1616/*We derive our classes from the c++ exception class: */
    1717class ErrorException: public exception {
    18        
     18
    1919        string   what_str;
    2020        string   function_name;
     
    2828        virtual const char *what() const throw();
    2929        void Report() const;
     30        const char* MatlabReport() const;
     31        const char* PythonReport() const;
    3032
    3133};
  • issm/trunk/src/c/shared/Exceptions/exprintf.cpp

    r12706 r13975  
    55 * ErrorException(exprintf("%s%i\n","test failed for id:",id));
    66 */
    7 
    87
    98#include <stdarg.h>
     
    1716        char *buffer = NULL;
    1817        int   n,size = 100;
    19         int   string_size;
    2018
    2119        //variable list of arguments
  • issm/trunk/src/c/shared/Exp/DomainOutlineWrite.cpp

    r13395 r13975  
    1212
    1313int DomainOutlineWrite(int nprof,int* profnvertices,double** pprofx,double** pprofy,bool* closed,char* domainname){
    14        
     14
    1515        /*Error management: */
    1616        int noerr=1;
     
    3333                fprintf(fid,"%s %s\n","##","Icon:0");
    3434                fprintf(fid,"%s %s %s %s\n","#","Points","Count","Value");
    35                
     35
    3636                /*Write number of profile vertices: */
    3737                fprintf(fid,"%u %s\n",profnvertices[counter]  ,"1.");
    38        
     38
    3939                /*Write next line: */
    4040                fprintf(fid,"%s %s %s %s %s\n","#","X","pos","Y","pos");
  • issm/trunk/src/c/shared/Exp/IsInPoly.cpp

    r13395 r13975  
    1818        int i, j, c = 0;
    1919        double n1, n2, normp, scalar;
    20        
     20
    2121        /*first test, are they colinear? if yes, is the point in the middle of the segment*/
    2222        if (edgevalue != 2 ){
  • issm/trunk/src/c/shared/Exp/IsInPolySerial.cpp

    r13395 r13975  
    55#include <math.h>
    66
    7 
    87#include "./exp.h"
    9 
    108
    119int IsInPolySerial(double* in,double* xc,double* yc,int numvertices,double* x,double* y,int nods, int edgevalue){
    1210
    13         int i,j;
    1411        double x0,y0;
    1512
    1613        /*Go through all vertices of the mesh:*/
    17         for (i=0;i<nods;i++){
     14        for(int i=0;i<nods;i++){
    1815                if (in[i]){
    1916                        /*this vertex already is inside one of the contours, continue*/
  • issm/trunk/src/c/shared/Exp/exp.h

    r13395 r13975  
    6060template <class doubletype>
    6161int DomainOutlineRead(int* pnprof,int** pprofnvertices,doubletype*** ppprofx,doubletype*** ppprofy,bool** pclosed,char* domainname){
    62        
     62
    6363        /*indexing: */
    6464        int i,counter;
     
    9090        nprof=1;
    9191        for(;;){
    92                 fscanf(fid,"%256s %256s\n",chardummy,chardummy);
    93                 fscanf(fid,"%256s %256s\n",chardummy,chardummy);
    94                 fscanf(fid,"%256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy);
    95                 fscanf(fid,"%20u %256s\n",&n,chardummy);
    96                 fscanf(fid,"%256s %256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy,chardummy);
     92                fscanf(fid,"%255s %255s\n",chardummy,chardummy);
     93                fscanf(fid,"%255s %255s\n",chardummy,chardummy);
     94                fscanf(fid,"%255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy);
     95                fscanf(fid,"%20u %255s\n",&n,chardummy);
     96                fscanf(fid,"%255s %255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy,chardummy);
    9797                for (i=0;i<n;i++) fscanf(fid,"%20lf %20lf\n",&ddummy,&ddummy);
    9898                /*check whether we are at the end of the file, otherwise, keep reading next profile:*/
     
    100100                nprof++;
    101101        }
    102        
     102
    103103        /*Allocate and initialize all the profiles: */
    104104        profnvertices = xNew<int>(nprof);
     
    118118
    119119                /*Skip header: */
    120                 fscanf(fid,"%256s %256s\n",chardummy,chardummy);
    121                 fscanf(fid,"%256s %256s\n",chardummy,chardummy);
    122                 fscanf(fid,"%256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy);
    123                
     120                fscanf(fid,"%255s %255s\n",chardummy,chardummy);
     121                fscanf(fid,"%255s %255s\n",chardummy,chardummy);
     122                fscanf(fid,"%255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy);
     123
    124124                /*Get number of profile vertices: */
    125                 fscanf(fid,"%20u %256s\n",&n,chardummy);
    126        
     125                fscanf(fid,"%20u %255s\n",&n,chardummy);
     126
    127127                /*Skip next line: */
    128                 fscanf(fid,"%256s %256s %256s %256s %256s\n",chardummy,chardummy,chardummy,chardummy,chardummy);
     128                fscanf(fid,"%255s %255s %255s %255s %255s\n",chardummy,chardummy,chardummy,chardummy,chardummy);
    129129
    130130                /*Allocate vertices: */
    131131                x=xNew<doubletype>(n);
    132132                y=xNew<doubletype>(n);
    133                
     133
    134134                /*Read vertices: */
    135135                for (i=0;i<n;i++){
     
    170170        doubletype         **pprofx        = NULL;
    171171        doubletype         **pprofy        = NULL;
    172         Contour<doubletype> *contour       = NULL;
    173172
    174173        /*output: */
  • issm/trunk/src/c/shared/MemOps/xMemCpy.h

    r12706 r13975  
    1717
    1818#endif
    19 
  • issm/trunk/src/c/shared/Numerics/BrentSearch.cpp

    r13395 r13975  
    4040        maxiter=optpars->maxiter;
    4141        cm_jump=optpars->cm_jump;
    42        
     42
    4343        /*initialize counter and get response at the boundaries*/
    4444        iter=0;
  • issm/trunk/src/c/shared/Numerics/IsInputConverged.cpp

    r13395 r13975  
    2020        /*output: */
    2121        IssmDouble eps;
    22        
     22
    2323        /*intermediary: */
    2424        IssmDouble *newvalues     = NULL;
  • issm/trunk/src/c/shared/Numerics/OptimalSearch.cpp

    r13395 r13975  
    3838        x2       =optpars->xmax;
    3939        maxiter  =optpars->maxiter;
    40        
     40
    4141        //get the value of the function at the first boundary
    4242        fx1= (*f)(x1,optargs);
  • issm/trunk/src/c/shared/Numerics/OptionsFromAnalysis.cpp

    r13395 r13975  
    1616
    1717char* OptionsFromAnalysis(Parameters* parameters,int analysis_type){
    18        
     18
    1919        /*output: */
    2020        char*   outstring=NULL;
  • issm/trunk/src/c/shared/Numerics/Synchronize.sh

    r12706 r13975  
    22#Synchronize Verbosity
    33#first remove existing files
    4 rm $ISSM_DIR/src/m/shared/Verb*.m
     4rm $ISSM_DIR/src/m/classes/Verb*.m
    55
    66echo "Synchronizing Verbosity levels..."
     
    5050        echo "$FILENAME -> 2^$POWER = $BINARY"
    5151
    52         #Add Verbosity Matlab file{{{
    53         cat <<END > $ISSM_DIR"/src/m/shared/"$(echo $FILENAME".m")
    54 function bool=$(echo $FILENAME)()
    55 %$(echo $FILENAME | awk {'print toupper($1)'}) - Return true if $(echo $LEVELNAME | awk {'print tolower($1)'}) level is activated
    56 %
    57 %   WARNING: DO NOT MODIFY THIS FILE
    58 %            this file has been automatically generated by src/c/shared/Numerics/Synchronize.sh
    59 %            Please read src/c/shared/Numerics/README for more information
    60 %
    61 %   Usage:
    62 %      bool=$FILENAME()
    63 
    64 bool=logical(bitand(GetVerbosityLevel(),$BINARY));
    65 END
    66         #}}}
    6752        #Add case to verbose.m FIELDS{{{
    6853        if [ $i -eq 1 ]; then cat <<END >> FIELDS
     
    135120void SetVerbosityLevel(int level){
    136121
    137         if(level<0) _error2_("vebosity level should be a positive integer (user provided " << level << ")");
     122        if(level<0) _error_("vebosity level should be a positive integer (user provided " << level << ")");
    138123
    139124        verbositylevel = level;
  • issm/trunk/src/c/shared/Numerics/UnitConversion.cpp

    r13395 r13975  
    4040}
    4141
    42 
    4342IssmDouble UnitConversionScaleFactor(int type_enum){
    4443
    4544        IssmDouble yts=365.0*24.0*3600.0;
    46        
     45
    4746        IssmDouble scale;
    4847        switch(type_enum){
     
    7271                case SurfaceforcingsANegEnum:                                           scale=yts;break;     //m/yr
    7372                case SurfaceforcingsBNegEnum:                                           scale=yts;break;     //m/yr
     73                case SurfaceforcingsSmbrefEnum:                                 scale=yts;break;     //m/yr
    7474                case MisfitEnum:                             scale=pow(yts,2);break; //(m/yr)^2
    7575                case MassFluxEnum:                           scale=pow((IssmDouble)10,-12)*yts;break; // (GigaTon/year)
  • issm/trunk/src/c/shared/Numerics/Verbosity.cpp

    r13395 r13975  
    2828bool VerboseControl(void){return (GetVerbosityLevel() & 32);} /* 2^5*/
    2929bool VerboseQmu(void){return (GetVerbosityLevel() & 64);} /* 2^6*/
     30bool VerboseAutodiff(void){return (GetVerbosityLevel() & 128);} /* 2^7*/
    3031
    3132/*Verbosity Setup*/
     
    4142/*FUNCTION GetVerbosityLevel {{{*/
    4243int  GetVerbosityLevel(void){
    43 
    4444        _assert_(verbositylevel>=0);
    4545        return verbositylevel;
    46 
    4746}/*}}}*/
  • issm/trunk/src/c/shared/Numerics/Verbosity.h

    r6324 r13975  
    1414bool VerboseControl(void);
    1515bool VerboseQmu(void);
     16bool VerboseAutodiff(void);
    1617
    1718/*Setup Verbosity level*/
  • issm/trunk/src/c/shared/Numerics/XZvectorsToCoordinateSystem.cpp

    r12706 r13975  
    77void XZvectorsToCoordinateSystem(IssmDouble* T,IssmDouble* xzvectors){
    88
    9         int             i,j;
    109        IssmDouble      x[3],y[3],z[3];
    1110        IssmDouble      x_norm, y_norm, z_norm;
    1211
    13         for(i=0;i<6;i++){
     12        for(int i=0;i<6;i++){
    1413                if(xIsNan<IssmDouble>(xzvectors[i])){
    1514                        /*At least one NaN found: default to Id*/
  • issm/trunk/src/c/shared/Numerics/cross.cpp

    r12706 r13975  
    2020
    2121}
    22 
  • issm/trunk/src/c/shared/Numerics/isnan.h

    r12706 r13975  
    66#define _XISNAN_H_
    77
    8 #include <cmath>
     8#ifdef HAVE_CONFIG_H
     9   #include <config.h>
     10#else
     11#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
     12#endif
     13
     14/*If include cmath instead of math, isnan on linux64 murdo does not work: */
     15#include <math.h>
    916
    1017template <class T> int xIsNan(const T& X) {
     
    1623}
    1724
    18 #ifdef _HAVE_ADOLC_
     25#if defined(_HAVE_ADOLC_) && !defined(_WRAPPERS_)
    1926template <> int xIsNan<adouble> (const adouble& X);
    2027#endif
  • issm/trunk/src/c/shared/Numerics/recast.h

    r12706 r13975  
    99#define _RECAST_H_
    1010
    11 #ifndef _HAVE_ADOLC_
     11#ifdef HAVE_CONFIG_H
     12   #include <config.h>
     13#else
     14#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
     15#endif
     16
     17#if !defined(_HAVE_ADOLC_) || defined(_WRAPPERS_)
    1218
    1319template<class To, class From>
  • issm/trunk/src/c/shared/Sorting/binary_search.cpp

    r12330 r13975  
    1111#include <stdio.h>
    1212
    13 int binary_search(int* poffset,int target,int* sorted_integers,int num_integers){
     13int binary_search(int* poffset,int target,int* sorted_integers,int num_integers){ /*{{{*/
    1414
    1515        /*output: */
     
    1818
    1919        /*intermediary: */
    20         int* beg=NULL;
    21         int* end=NULL;
    22         int* mid=NULL;
     20        int *beg = NULL;
     21        int *end = NULL;
     22        int *mid = NULL;
    2323
    2424        // point to beginning and end of the array
     
    4747                        }
    4848                }
    49                          
     49
    5050                //did we find the target?
    5151                if (*mid == target) {
     
    6060        /*Assign output pointers:*/
    6161        *poffset=offset;
    62        
     62
    6363        /*Return result: */
    6464        return found;
    65 }
     65} /*}}}*/
  • issm/trunk/src/c/shared/Sorting/sorting.h

    r12330 r13975  
    77
    88int binary_search(int* poffset,int target,int* sorted_integers,int num_integers);
     9template <typename doubletype> int binary_search(int* poffset,doubletype target,doubletype* list,int length){ /*{{{*/
     10        /*
     11         *             l[0]  l[1]  l[2]        l[n]  l[n+1]   l[length-1]
     12         *     <-------+-----+-----+-----+ ... +-----+........+-------------->
     13         * offset: -1     0     1     2           n              length -1
     14         * 
     15         *  offset = -1        target < list[0]
     16         *  offset = n         list[n] <= target < list[n+1]
     17         *  offset = length-1  list[length-1] <= target
     18         */
     19
     20        /*output: */
     21        int offset = 0;
     22        int found  = 0;
     23
     24        /*intermediary: */
     25        int n0 = 0;
     26        int n1 = int(length/2);
     27        int n2 = length-1;
     28
     29        if(target<list[n0]){
     30                found  = 1;
     31                offset = -1;
     32        }
     33        else if(target>=list[n2]){
     34                found  = 1;
     35                offset = length-1;
     36        }
     37        else{
     38                for(;;){
     39                        /*did we find the target?*/
     40                        if(list[n1]<=target && list[n1+1]>target){
     41                                found  = 1;
     42                                offset = n1;
     43                                break;
     44                        }
     45                        else if(target < list[n1]){
     46                                n2 = n1;
     47                                n1 = n0 + int((n2-n0)/2);
     48                        }
     49                        else{
     50                                n0 = n1;
     51                                n1 = n0 + int((n2-n0)/2);
     52                        }
     53                }
     54        }
     55
     56        /*Assign output pointer and return*/
     57        *poffset=offset;
     58        return found;
     59} /*}}}*/
    960
    1061#endif //ifndef _SORTING_H_
  • issm/trunk/src/c/shared/String/DescriptorIndex.cpp

    r13395 r13975  
    1818
    1919int  DescriptorIndex(char* root, int* pindex,char* descriptor){ //We assume root has already been allocated, and we just have to copy into it.
    20        
     20
    2121        char * pch=NULL;
    2222
  • issm/trunk/src/c/shared/String/sharedstring.h

    r5469 r13975  
    88int  DescriptorIndex(char* root, int* pindex,char* descriptor);
    99
     10#ifndef WIN32
     11int stricmp(const char* a,const char* b);
     12#endif
     13
    1014#endif //ifndef _SHAREDSTRING_H_
    11 
  • issm/trunk/src/c/shared/Threads/LaunchThread.cpp

    r13395 r13975  
    3131        pthread_t      *threads = NULL;
    3232        pthread_handle *handles = NULL;
    33        
     33
    3434        /*dynamically allocate: */
    3535        threads=xNew<pthread_t>(num_threads);
     
    5252                }
    5353        }
    54        
     54
    5555        /*Free ressources:*/
    5656        xDelete<pthread_t>(threads);
     
    6262        handle.id=0;
    6363        handle.num=1;
    64        
     64
    6565        function((void*)&handle);
    6666        #endif
  • issm/trunk/src/c/shared/Threads/PartitionRange.cpp

    r9320 r13975  
    1616        int i0=-1;
    1717        int i1=-1;
    18        
     18
    1919        int step;
    2020        int i;
    21 
    2221
    2322        /*distribute elements across threads :*/
     
    2928        }
    3029
    31 
    3230        /*Assign output pointers:*/
    3331        *pi0=i0;
  • issm/trunk/src/c/shared/Threads/issm_threads.h

    r2549 r13975  
    1414} pthread_handle;
    1515
    16 
    1716/*routine that launches "function" in a multi-threaded way if requested,
    1817 * or just serially if not requested: */
  • issm/trunk/src/c/shared/TriMesh/AssociateSegmentToElement.cpp

    r8301 r13975  
    66
    77int AssociateSegmentToElement(double** psegments,int nseg, double* index,int nel){
    8        
     8
    99        /*Error management: */
    1010        int i;
     
    3030        return noerr;
    3131}
    32 
    33 
  • issm/trunk/src/c/shared/TriMesh/OrderSegments.cpp

    r11237 r13975  
    66
    77int OrderSegments(double** psegments,int nseg, double* index,int nel){
    8        
     8
    99        /*Error management: */
    1010        int i;
     
    1818        /*element indices: */
    1919        int el;
    20 
    2120
    2221        /*Recover segments: */
  • issm/trunk/src/c/shared/TriMesh/SplitMeshForRifts.cpp

    r13395 r13975  
    1212        x and y of size nodsx1
    1313        segments of size nsegsx3*/
    14        
     14
    1515        /*Error management: */
    1616        int noerr=1;
    17        
     17
    1818        int i,j,k,l;
    1919        int node;
     
    2323        int* riftsegments=NULL;
    2424        int* flags=NULL;
    25        
     25
    2626        int  NumGridElementListOnOneSideOfRift;
    2727        int* GridElementListOnOneSideOfRift=NULL;
     
    5555        for (i=0;i<nriftsegs;i++){
    5656                for (j=0;j<2;j++){
    57        
     57
    5858                        node=riftsegments[4*i+j+2];
    5959                        if(flags[node-1]){
     
    6666
    6767                        if(IsGridOnRift(riftsegments,nriftsegs,node)){
    68                        
     68
    6969                                DetermineGridElementListOnOneSideOfRift(&NumGridElementListOnOneSideOfRift,&GridElementListOnOneSideOfRift,i,nriftsegs,riftsegments,node,index,nel);
    70                        
     70
    7171                                /*Summary: we have for node, a list of elements
    7272                                 * (GridElementListOnOneSideOfRift, of size
  • issm/trunk/src/c/shared/TriMesh/TriMeshUtils.cpp

    r13395 r13975  
    1717        /*Does this node belong to 4 elements, or just 2? If it belongs to 4 elements, it is inside a rift,
    1818         *if it belongs to 2 elements, it is on the tip of a rift, or it has already been split across the rift (see below).*/
    19        
     19
    2020        int i;
    2121        int j;
     
    119119/*FUNCTION RiftSegmentsFromSegments{{{*/
    120120void RiftSegmentsFromSegments(int* pnriftsegs, int** priftsegments, int nel, double* index, int nsegs,double* segments){
    121        
     121
    122122        int i,counter;
    123123        int el,el2;
    124        
     124
    125125        int  nriftsegs;
    126126        int* riftsegments=NULL;
     
    179179
    180180        xDelete<int>(riftsegments_uncompressed);
    181        
     181
    182182        /*Assign output pointers: */
    183183        *priftsegments=riftsegments;
     
    266266        /*Reallocate segments: */
    267267        segments         =xReNew<double>(segments,         nsegs*3,(nsegs+nriftsegs)*3);
    268         segmentmarkerlist=xReNew<double>(segmentmarkerlist,nsegs*3,(nsegs+nriftsegs)*3);
     268        segmentmarkerlist=xReNew<double>(segmentmarkerlist,nsegs,(nsegs+nriftsegs));
    269269
    270270        /*First, update the existing segments to the new nodes :*/
     
    344344        *psegmentmarkerlist=segmentmarkerlist;
    345345        *pnsegs=nsegs;
    346        
     346
    347347        return noerr;
    348 }/*}}}*/
    349 /*FUNCTION pnpoly{{{*/
    350 int pnpoly(int npol, double *xp, double *yp, double x, double y) {
    351         int i, j, c = 0;
    352         for (i = 0, j = npol-1; i < npol; j = i++) {
    353                 if ((((yp[i]<=y) && (y<yp[j])) ||
    354                                         ((yp[j]<=y) && (y<yp[i]))) &&
    355                                 (x < (xp[j] - xp[i]) * (y - yp[i]) / (yp[j] - yp[i]) + xp[i]))
    356                         c = !c;
    357         }
    358         return c;
    359348}/*}}}*/
    360349/*FUNCTION FindElement{{{*/
     
    384373        double *segmentmarkerlist = NULL;
    385374        int numsegs;
    386        
     375
    387376        /*output: */
    388377        int      new_numsegs;
     
    460449/*FUNCTION PairRiftElements{{{*/
    461450int PairRiftElements(int** priftsnumpairs, double*** priftspairs,int numrifts,int* riftsnumsegments, double** riftssegments,double* x,double* y){
    462 
    463451
    464452        int noerr=1;
     
    693681        int i;
    694682        int noerr=1;
    695        
     683
    696684        /*output: */
    697685        int riftflag=0;
     
    717705/*FUNCTION OrderRifts{{{*/
    718706int OrderRifts(double** priftstips, double** riftssegments,double** riftspairs,int numrifts,int* riftsnumsegments,double* x,double* y,int nods,int nels){
    719        
     707
    720708        int noerr=1;
    721709        int i,j,k,counter;
     
    747735                riftpairs=riftspairs[i];
    748736                numsegs=riftsnumsegments[i];
    749        
     737
    750738                /*Allocate copy of riftsegments and riftpairs,
    751739                 *as well as ordering vector: */
     
    793781                                }
    794782                        }
    795                
     783
    796784                        if (node4==node2){
    797785                                /*node2 is a tip*/
     
    818806                                node1=(int)*(riftsegments+3*j+0);
    819807                                node2=(int)*(riftsegments+3*j+1);
    820                                
     808
    821809                                if ((node1==node) || (node2==node)){
    822810                                        /*Ok, this segment is connected to node, plug its index into order, unless we already plugged it before: */
     
    851839                        *(riftpairs_copy+2*j+1)=*(riftpairs+2*order[j]+1);
    852840                }
    853                
     841
    854842                for (j=0;j<numsegs;j++){
    855843                        *(riftsegments+3*j+0)=*(riftsegments_copy+3*j+0);
     
    873861int PenaltyPairs(double*** priftspenaltypairs,int** priftsnumpenaltypairs,int numrifts,double** riftssegments,
    874862                int* riftsnumsegs,double** riftspairs,double* riftstips,double* x,double* y){
    875                
    876863
    877864        int noerr=1;
     
    906893                /*allocate riftpenaltypairs, and riftnumpenaltypairs: */
    907894                if((numsegs/2-1)!=0)riftpenaltypairs=xNewZeroInit<double>((numsegs/2-1)*RIFTPENALTYPAIRSWIDTH);
    908                
     895
    909896                /*Go through only one flank of the rifts, not counting the tips: */
    910897                counter=0;
     
    997984                        *(riftpenaltypairs+j*7+5)=*(riftpenaltypairs+j*7+5)/magnitude;
    998985                }
    999                
     986
    1000987                riftspenaltypairs[i]=riftpenaltypairs;
    1001988                riftsnumpenaltypairs[i]=(numsegs/2-1);
     
    10351022        y=*py;
    10361023        nods=*pnods;
    1037 
    10381024
    10391025        for (i=0;i<num_seg;i++){
  • issm/trunk/src/c/shared/TriMesh/trimesh.h

    r12330 r13975  
    2222int DetermineGridElementListOnOneSideOfRift(int* pNumGridElementListOnOneSideOfRift, int** pGridElementListOnOneSideOfRift, int segmentnumber, int nriftsegs, int* riftsegments, int node,double* index,int nel);
    2323int UpdateSegments(double** psegments,double** psegmentmarkerlist, int* pnsegs, double* index, double* x,double* y,int* riftsegments,int nriftsegs,int nods,int nel);
    24 int pnpoly(int npol, double *xp, double *yp, double x, double y);
    2524int FindElement(double A,double B,double* index,int nel);
    2625int RemoveRifts(double** pindex,double** px,double** py,int* pnods,double** psegments,int* pnumsegs,int numrifts1,int* rifts1numsegs,double** rifts1segments,double** rifts1pairs,int nel);
  • issm/trunk/src/c/shared/shared.h

    r13395 r13975  
    66#define _SHARED_H_
    77
    8 #include "Alloc/alloc.h"
    9 #include "Alloc/xNewDelete.h"
    10 #include "Bamg/shared.h"
    11 #include "Elements/elements.h"
    12 #include "Exceptions/exceptions.h"
    13 #include "Exp/exp.h"
    14 #include "Matrix/matrix.h"
    15 #include "MemOps/xMemCpy.h"
    16 #include "Numerics/numerics.h"
    17 #include "Sorting/sorting.h"
    18 #include "Sys/sys.h"
    19 #include "Threads/issm_threads.h"
    20 #include "TriMesh/trimesh.h"
    21 #include "Wrapper/wrappershared.h"
     8#include "./Alloc/alloc.h"
     9#include "./Alloc/xNewDelete.h"
     10#include "./Bamg/shared.h"
     11#include "./Elements/elements.h"
     12#include "./Exceptions/exceptions.h"
     13#include "./Exp/exp.h"
     14#include "./Matrix/matrix.h"
     15#include "./MemOps/xMemCpy.h"
     16#include "./Numerics/numerics.h"
     17#include "./Sorting/sorting.h"
     18#include "./String/sharedstring.h"
     19#include "./Threads/issm_threads.h"
     20#include "./TriMesh/trimesh.h"
    2221
    2322#endif
  • issm/trunk/src/c/solutions/AdjointCorePointerFromSolutionEnum.cpp

    r13395 r13975  
    1 /*!\file:  CorePointerFromSolutionEnum.cpp
     1/*!\file:  AdjointCorePointerFromSolutionEnum.cpp
    22 * \brief: return type of analyses, number of analyses and core solution function.
    33 */
     
    2424
    2525        switch(solutiontype){
    26        
     26
    2727                case DiagnosticSolutionEnum:
    2828                        adjointcore=&adjointdiagnostic_core;
     
    3838                        break;
    3939        }
    40        
     40
    4141        /*Assign output pointer:*/
    4242        _assert_(padjointcore);
  • issm/trunk/src/c/solutions/AnalysisConfiguration.cpp

    r13395 r13975  
    2626        /*Analyses lists*/
    2727        switch(solutiontype){
    28        
     28
    2929                case DiagnosticSolutionEnum:
    3030                        numanalyses=5;
     
    5656                        analyses[1]=MeltingAnalysisEnum;
    5757                        break;
    58                
     58
    5959                case EnthalpySolutionEnum:
    6060                        numanalyses=1;
     
    6262                        analyses[0]=EnthalpyAnalysisEnum;
    6363                        break;
    64                
     64
    6565                case HydrologySolutionEnum:
    6666                        numanalyses=3;
     
    108108                        analyses[8]=PrognosticAnalysisEnum;
    109109                        break;
    110                
     110
    111111                default:
    112112                        _error_("solution type: " << EnumToStringx(solutiontype) << " not supported yet!");
  • issm/trunk/src/c/solutions/CorePointerFromSolutionEnum.cpp

    r13395 r13975  
    2424
    2525        switch(solutiontype){
    26        
     26
    2727                case DiagnosticSolutionEnum:
    2828                        #ifdef _HAVE_DIAGNOSTIC_
     
    9999                        break;
    100100        }
    101        
     101
    102102        /*Assign output pointer:*/
    103103        _assert_(psolutioncore);
  • issm/trunk/src/c/solutions/ProcessArguments.cpp

    r13395 r13975  
    1919        char *rootpatharg    = NULL;
    2020
    21         *solution_type=StringToEnumx(argv[1]);
     21        /*Check input arguments*/
    2222        if(argc<2)_error_("Usage error: no solution requested");
    2323        if(argc<3)_error_("Usage error: missing execution directory");
    2424        if(argc<4)_error_("Usage error: missing model name");
     25
     26        /*Get requested solution*/
     27        *solution_type=StringToEnumx(argv[1]);
    2528
    2629        rootpatharg=argv[2];
  • issm/trunk/src/c/solutions/ResetBoundaryConditions.cpp

    r13395 r13975  
    99
    1010void ResetBoundaryConditions(FemModel* femmodel, int analysis_type){
    11        
     11
    1212        /*variables: */
    1313        Vector<IssmDouble>*    yg    = NULL;
    1414        Nodes *nodes = NULL;
    15         int    i;
    1615
    1716        if(VerboseSolution()) _pprintLine_("   updating boundary conditions...");
    18                        
     17
    1918        /*set current analysis: */
    2019        femmodel->SetCurrentConfiguration(analysis_type);
  • issm/trunk/src/c/solutions/adjointbalancethickness_core.cpp

    r13395 r13975  
    1414
    1515void adjointbalancethickness_core(FemModel* femmodel){
    16        
     16
    1717        /*parameters: */
    1818        bool save_results;
     
    3333        femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum,AdjointBalancethicknessAnalysisEnum);
    3434        solver_adjoint_linear(femmodel);
    35        
     35
    3636        /*Save results*/
    3737        if(save_results){
  • issm/trunk/src/c/solutions/adjointdiagnostic_core.cpp

    r13395 r13975  
    1414
    1515void adjointdiagnostic_core(FemModel* femmodel){
    16        
     16
    1717        /*parameters: */
    1818        bool isstokes;
     
    3636        femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum,AdjointHorizAnalysisEnum);
    3737        solver_adjoint_linear(femmodel);
    38        
     38
    3939        /*Save results*/
    4040        if(save_results){
  • issm/trunk/src/c/solutions/balancethickness_core.cpp

    r13395 r13975  
    2020        /*activate formulation: */
    2121        femmodel->SetCurrentConfiguration(BalancethicknessAnalysisEnum);
    22        
     22
    2323        /*recover parameters: */
    2424        femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
  • issm/trunk/src/c/solutions/bedslope_core.cpp

    r13395 r13975  
    2626        femmodel->SetCurrentConfiguration(BedSlopeAnalysisEnum,BedSlopeYAnalysisEnum);
    2727        solver_linear(femmodel);
    28        
     28
    2929        if(save_results){
    3030                if(VerboseSolution()) _pprintLine_("   saving results");
  • issm/trunk/src/c/solutions/control_core.cpp

    r13395 r13975  
    1616
    1717        int     i,n;
    18        
     18
    1919        /*parameters: */
    2020        int     num_controls,num_responses;
     
    3232        IssmDouble* maxiter=NULL;
    3333        IssmDouble* cm_jump=NULL;
    34                
     34
    3535        /*intermediary: */
    3636        IssmDouble  search_scalar=1;
     
    7272        J=xNew<IssmDouble>(nsteps);
    7373        step_responses=xNew<int>(num_responses);
    74                
     74
    7575        /*Initialize some of the BrentSearch arguments: */
    7676        optargs.femmodel=femmodel;
    7777        optpars.xmin=0; optpars.xmax=1;
    78        
     78
    7979        /*Start looping: */
    8080        for(n=0;n<nsteps;n++){
     
    8484                for(i=0;i<num_responses;i++) step_responses[i]=reCast<int,IssmDouble>(responses[n*num_responses+i]);
    8585                femmodel->parameters->SetParam(step_responses,1,num_responses,StepResponsesEnum);
    86                
     86
    8787                /*In steady state inversion, compute new temperature field now*/
    8888                if(solution_type==SteadystateSolutionEnum) solutioncore(femmodel);
     
    104104                if(VerboseControl()) _pprintLine_("   updating parameter using optimized search scalar"); //true means update save controls
    105105                InputControlUpdatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,search_scalar,true);
    106                
     106
    107107                if(controlconvergence(J[n],tol_cm)) break;
    108108        }
  • issm/trunk/src/c/solutions/controlconvergence.cpp

    r13395 r13975  
    1919bool controlconvergence(IssmDouble J, IssmDouble tol_cm){
    2020
    21         int i;
    2221        bool converged=false;
    2322
  • issm/trunk/src/c/solutions/controltao_core.cpp

    r13395 r13975  
    5454
    5555        /*Initialize TAO*/
    56         TaoCreate(PETSC_COMM_WORLD,&tao);
     56        TaoCreate(IssmComm::GetComm(),&tao);
    5757        if(VerboseControl()) _pprintLine_("   Initializing the Toolkit for Advanced Optimization (TAO)");
    5858        TaoSetFromOptions(tao);
     
    9999        /*Clean up and return*/
    100100        xDelete<int>(control_list);
     101        xDelete<double>(user.J);
    101102        xdelete(&X);
    102103        TaoDestroy(&tao);
     
    141142
    142143        /*Compute objective function*/
    143         CostFunctionx(fcn,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
     144        femmodel->CostFunctionx(fcn);
    144145
    145146        /*Compute gradient*/
     
    173174        /*Retrieve objective functions independently*/
    174175        for(i=0;i<num_responses;i++){
    175                 Responsex(&f,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,EnumToStringx(responses[i]),false,i);
     176                femmodel->Responsex(&f,EnumToStringx(responses[i]),false,i);
    176177                _pprintString_(" "<<setw(12)<<setprecision(7)<<f);
    177178        }
  • issm/trunk/src/c/solutions/diagnostic_core.cpp

    r13395 r13975  
    6060
    6161        if(ishutter){
    62                        
     62
    6363                if(VerboseSolution()) _pprintLine_("   computing hutter velocities");
    6464
     
    6868                femmodel->SetCurrentConfiguration(DiagnosticHutterAnalysisEnum);
    6969                solver_linear(femmodel);
    70                
     70
    7171                if (ismacayealpattyn) ResetBoundaryConditions(femmodel,DiagnosticHorizAnalysisEnum);
    7272        }
    7373
    7474        if ((ismacayealpattyn || isl1l2) ^ isstokes){ // ^ = xor
    75                
     75
    7676                if(VerboseSolution()) _pprintLine_("   computing velocities");
    7777                femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
     
    9595        }
    9696
    97 
    9897        if(save_results){
    9998                if(VerboseSolution()) _pprintLine_("   saving results");
     
    103102                InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,PressureEnum);
    104103                if(dim==3) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VzEnum);
    105                 RequestedOutputsx(femmodel->results,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,requested_outputs,numoutputs);
     104                femmodel->RequestedOutputsx(requested_outputs,numoutputs);
    106105        }
     106
     107        if(solution_type==DiagnosticSolutionEnum)femmodel->RequestedDependentsx();
    107108
    108109        /*Free ressources:*/
  • issm/trunk/src/c/solutions/hydrology_core.cpp

    r13395 r13975  
    4444        /*Loop through time: */
    4545        for(i=0;i<nsteps;i++){
    46                
     46
    4747                if(nsteps)if(VerboseSolution()) _pprintLine_("time step:" << i+1 << "/" << nsteps);
    4848                time+=dt;
     
    5757                        //InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,HydrologyWaterVxEnum,i+1,time);
    5858                        //InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,HydrologyWaterVyEnum,i+1,time);
    59                        
     59
    6060                        /*unload results*/
    6161                        if(VerboseSolution()) _pprintLine_("   saving temporary results");
     
    6464        }
    6565}
    66 
  • issm/trunk/src/c/solutions/hydrology_core_step.cpp

    r13395 r13975  
    1414
    1515void hydrology_core_step(FemModel* femmodel,int step, IssmDouble time){
    16        
     16
    1717        bool modify_loads=true;
    1818
  • issm/trunk/src/c/solutions/issm.cpp

    r13395 r13975  
    11/*!\file:  issm.cpp
    2  * \brief: ISSM main parallel program
     2 * \brief: ISSM main program
    33 */
    44
    55#include "../issm.h"
    6 #include "../include/globals.h"
    7 #include "../shared/Numerics/adolc_edf.h"
    86
    97int main(int argc,char **argv){
    108
    11         /*I/O: */
    12         FILE *output_fid       = NULL;
    13         FILE *petscoptionsfid  = NULL;
    14         bool  waitonlock       = false;
    15         bool  dakota_analysis,control_analysis,tao_analysis;
     9        /*Initialize exception trapping: */
     10        ExceptionTrapBegin();
    1611
    17         /*AD: */
    18         bool autodiff=false;
    19         size_t   tape_stats[11];
     12        /*Initialize environment (MPI, PETSC, MUMPS, etc ...)*/
     13        COMM comm_init=EnvironmentInit(argc,argv);
    2014
    21         /*FemModel: */
    22         FemModel *femmodel = NULL;
     15        /*Initialize femmodel from arguments provided command line: */
     16        FemModel *femmodel = new FemModel(argc,argv,comm_init);
    2317
    24         /*configuration: */
    25         void (*solutioncore)(FemModel*)=NULL; //core solution function pointer
    26         int* analyses=NULL;
    27         int  numanalyses;
    28         int  solution_type;
     18        /*Solve: */
     19        femmodel->Solve();
    2920
    30         /*File names*/
    31         char *lockfilename   = NULL;
    32         char *binfilename    = NULL;
    33         char *outbinfilename = NULL;
    34         char *petscfilename  = NULL;
    35         char *rootpath       = NULL;
     21        /*Output results: */
     22        femmodel->OutputResults();
    3623
    37         /*time*/
    38         IssmPDouble   start, finish;
    39         IssmPDouble   start_core, finish_core;
    40         IssmPDouble   start_init, finish_init;
    41         int      ierr;
    42 
    43         /*profiling*/   
    44         bool profiling = false;
    45         IssmPDouble Time_start, Flops_start;
    46         IssmPDouble Solution_time, Memory_use, Current_flops;
    47 
    48         ISSMBOOT();
    49 
    50        
    51         /*Initialize environments: Petsc, MPI, etc...: */
    52         #ifdef _HAVE_PETSC_
    53         ierr=PetscInitialize(&argc,&argv,(char*)0,""); 
    54         if(ierr) _error_("Could not initialize Petsc");
    55         #else
    56         #ifdef _HAVE_MPI_
    57         MPI_Init(&argc,&argv);
    58         #endif
    59         #endif
    60 
    61         #ifdef _HAVE_MPI_
    62         MPI_Barrier(MPI_COMM_WORLD); start=MPI_Wtime();
    63         #else
    64         start=(IssmPDouble)clock();
    65         #endif
    66 
    67         /*Size and rank: */
    68         #ifdef _HAVE_MPI_
    69         MPI_Comm_rank(MPI_COMM_WORLD,&my_rank); 
    70         MPI_Comm_size(MPI_COMM_WORLD,&num_procs);
    71         #endif
    72 
    73         /*First process inputs*/
    74         _pprintLine_("");
    75         _pprintLine_("Ice Sheet System Model (" << PACKAGE_NAME << ") version " << PACKAGE_VERSION);
    76         _pprintLine_("(website: " << PACKAGE_URL << " contact: " << PACKAGE_BUGREPORT << ")");
    77         _pprintLine_("");
    78         ProcessArguments(&solution_type,&binfilename,&outbinfilename,&petscfilename,&lockfilename,&rootpath,argc,argv);
    79 
    80         /*out of solution_type, figure out types of analyses needed in the femmodel: */
    81         AnalysisConfiguration(&analyses,&numanalyses,solution_type);
    82 
    83         /*before we create the model, start the trace on for AD mode: */
    84         #ifdef _HAVE_ADOLC_
    85         trace_on(1);
    86         #endif
    87 
    88         /*Create femmodel, using input file: */
    89         #ifdef _HAVE_MPI_
    90         MPI_Barrier(MPI_COMM_WORLD); start_init=MPI_Wtime();
    91         #else
    92         start_init=(IssmPDouble)clock();
    93         #endif
    94         femmodel=new FemModel(rootpath,binfilename,outbinfilename,solution_type,analyses,numanalyses);
    95        
    96         /*get type of solution we are going to run: */
    97         CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
    98 
    99         /*Open output file once for all*/
    100         output_fid=pfopen(outbinfilename,"wb");
    101         femmodel->parameters->SetParam(output_fid,OutputFilePointerEnum);
    102 
    103         /*add petsc options to parameters: */
    104         petscoptionsfid=pfopen(petscfilename,"r");
    105         ParsePetscOptionsx(femmodel->parameters,petscoptionsfid);
    106         pfclose(petscoptionsfid,petscfilename);
    107 
    108         /*get parameters: */
    109         femmodel->parameters->FindParam(&waitonlock,SettingsWaitonlockEnum);
    110         femmodel->parameters->FindParam(&dakota_analysis,QmuIsdakotaEnum);
    111         femmodel->parameters->FindParam(&control_analysis,InversionIscontrolEnum);
    112         femmodel->parameters->FindParam(&tao_analysis,InversionTaoEnum);
    113         femmodel->parameters->FindParam(&profiling,DebugProfilingEnum);
    114         femmodel->parameters->FindParam(&autodiff,AutodiffIsautodiffEnum);
    115 
    116         #ifdef _HAVE_MPI_
    117         MPI_Barrier(MPI_COMM_WORLD); finish_init=MPI_Wtime();
    118         #else
    119         finish_init=(IssmPDouble)clock();
    120         #endif
    121        
    122         /*If running AD, then initialize the tape: */
    123         #ifdef _HAVE_ADOLC_
    124         GenericParam<Adolc_edf> *theAdolcEDF_p=new GenericParam<Adolc_edf>(AdolcParamEnum);
    125         theAdolcEDF_p->GetParameterValue().myEDF_for_solverx_p=reg_ext_fct(EDF_for_solverx);
    126         femmodel->parameters->AddObject(theAdolcEDF_p);
    127         #else
    128         if(autodiff) _error_("ISSM was not compiled with ADOLC support, cannot carry out autodiff analysis!");
    129         #endif
    130 
    131         _pprintLine_("call computational core:");
    132         #ifdef _HAVE_MPI_
    133         MPI_Barrier(MPI_COMM_WORLD); start_core=MPI_Wtime( );
    134         #else
    135         start_core=(IssmPDouble)clock();
    136         #endif
    137        
    138         if(profiling)ProfilingStart(&Time_start,&Flops_start);
    139 
    140         if(dakota_analysis){
    141                 #ifdef _HAVE_DAKOTA_
    142                 Dakotax(femmodel);
    143                 #else
    144                 _error_("ISSM was not compiled with dakota support, cannot carry out dakota analysis!");
    145                 #endif
    146         }
    147         else if(control_analysis){
    148                 #ifdef _HAVE_CONTROL_
    149                 if(tao_analysis)
    150                  controltao_core(femmodel);
    151                 else
    152                  control_core(femmodel);
    153                 #else
    154                 _error_("ISSM was not compiled with control support, cannot carry out dakota analysis!");
    155                 #endif
    156         }
    157         else{
    158                 solutioncore(femmodel);
    159         }
    160 
    161         if(profiling){
    162                 ProfilingEnd(&Solution_time,&Memory_use,&Current_flops,Time_start,Flops_start);
    163                 femmodel->results->AddObject(new GenericExternalResult<double>(femmodel->results->Size()+1, ProfilingSolutionTimeEnum, Solution_time, 1, 0));
    164                 femmodel->results->AddObject(new GenericExternalResult<double>(femmodel->results->Size()+1, ProfilingCurrentMemEnum, Memory_use, 1, 0));
    165                 femmodel->results->AddObject(new GenericExternalResult<double>(femmodel->results->Size()+1, ProfilingCurrentFlopsEnum, Current_flops, 1, 0));
    166         }
    167 
    168         #ifdef _HAVE_ADOLC_
    169         if(autodiff){
    170                 trace_off();
    171                 AutodiffDriversx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
    172         }
    173         #endif
    174 
    175 
    176         #ifdef _HAVE_MPI_
    177         MPI_Barrier(MPI_COMM_WORLD); finish_core=MPI_Wtime( );
    178         #else
    179         finish_core=(IssmPDouble)clock();
    180         #endif
    181        
    182         _pprintLine_("write results to disk:");
    183         OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
    184        
    185         /*If running AD, close our tape, print statistics: {{{*/
    186         #ifdef _HAVE_ADOLC_
    187         if(autodiff){
    188                 tapestats(1,tape_stats); //reading of tape statistics
    189                 _pprintLine_("   ADOLC statistics: ");
    190                 _pprintLine_("   "<<setw(45)<<left<<"Number of independents: " <<tape_stats[0]);
    191                 _pprintLine_("   "<<setw(45)<<left<<"Number of dependents: " <<tape_stats[1]);
    192                 _pprintLine_("   "<<setw(45)<<left<<"Maximal number of live active variables: " <<tape_stats[2]);
    193                 _pprintLine_("   "<<setw(45)<<left<<"Size of value stack (number of overwrites): " <<tape_stats[3]);
    194                 _pprintLine_("   "<<setw(45)<<left<<"Buffer size (a multiple of eight): " <<tape_stats[4]);
    195                 _pprintLine_("   "<<setw(45)<<left<<"Total number of operations recorded: " <<tape_stats[5]);
    196         }
    197         #endif  /*}}}*/
    198 
    199         /*Close output and petsc options file and write lock file if requested*/
    200         pfclose(output_fid,lockfilename);
    201         if (waitonlock>0){
    202                 _pprintLine_("write lock file:");
    203                 WriteLockFile(lockfilename);
    204         }
    205 
    206         /*Free resources */
    207         xDelete<int>(analyses);
    208         xDelete<char>(lockfilename);
    209         xDelete<char>(binfilename);
    210         xDelete<char>(outbinfilename);
    211         xDelete<char>(petscfilename);
    212         xDelete<char>(rootpath);
     24        /*Wrap up: */
    21325        delete femmodel;
    21426
    215         /*Get finish time and close*/
    216         #ifdef _HAVE_MPI_
    217         MPI_Barrier(MPI_COMM_WORLD); finish = MPI_Wtime( );
    218         _pprintLine_("");
    219         _pprintLine_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<finish_init-start_init);
    220         _pprintLine_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<finish_core-start_core);
    221         _pprintLine_("");
    222         _pprintLine_("   Total elapsed time:"<<int((finish-start)/3600)<<" hrs "<<int(int(finish-start)%3600/60)<<" min "<<int(finish-start)%60<<" sec");
    223         _pprintLine_("");
    224         #else
    225         finish=(IssmPDouble)clock();
    226         _pprintLine_("");
    227         _pprintLine_("   "<<setw(40)<<left<<"FemModel initialization elapsed time:"<<(finish_init-start_init)/CLOCKS_PER_SEC);
    228         _pprintLine_("   "<<setw(40)<<left<<"Core solution elapsed time:"<<(finish_core-start_core)/CLOCKS_PER_SEC);
    229         _pprintLine_("");
    230         _pprintLine_("   Total elapsed time:"
    231                                 <<int((finish-start)/CLOCKS_PER_SEC/3600)<<" hrs "
    232                                 <<int(int(finish-start)/CLOCKS_PER_SEC%3600/60)<<" min "
    233                                 <<int(finish-start)/CLOCKS_PER_SEC%60<<" sec");
    234         _pprintLine_("");
    235         #endif
    236        
    237         #ifdef _HAVE_PETSC_
    238         _pprintLine_("closing MPI and Petsc");
    239         PetscFinalize();
    240         #else
    241         #ifdef _HAVE_MPI_
    242         _pprintLine_("closing MPI and Petsc");
    243         MPI_Finalize();
    244         #endif
    245         #endif
     27        /*Finalize environment:*/
     28        EnvironmentFinalize();
    24629
    247        
    248         /*end module: */
    249         ISSMEND();
     30        /*Finalize exception trapping: */
     31        ExceptionTrapEnd();
    25032
    251         return 0; //unix success return;
     33        /*Return unix success: */
     34        return 0;
    25235}
  • issm/trunk/src/c/solutions/kriging.cpp

    r13395 r13975  
    44
    55#include "../issm.h"
    6 #include "../include/globals.h"
    76
    87/*Local prototypes*/
    98void ProcessArguments2(char** pbinfilename,char** poutbinfilename,char** plockfilename,char** prootpath,int argc,char **argv);
    109void ProcessInputfile(IssmDouble **px,IssmDouble **py,IssmDouble **pdata,int *pnobs,IssmDouble **px_interp,IssmDouble **py_interp,int *pninterp,Options **poptions,FILE* fid);
     10
     11int my_rank;
     12int num_procs;
    1113
    1214int main(int argc,char **argv){
     
    2325        char *rootpath       = NULL;
    2426
     27        MPI_Comm comm;
     28        extern int my_rank;
     29        extern int num_procs;
     30
    2531        /*Input*/
    2632        int         ninterp,nobs;
     
    3642        IssmDouble *error       = NULL;
    3743
    38         ISSMBOOT();
     44        /*Initialize exception trapping: */
     45        ExceptionTrapBegin();
    3946
    40         /*Initialize environments: Petsc, MPI, etc...: */
    41 #ifdef _HAVE_PETSC_
    42         int ierr=PetscInitialize(&argc,&argv,(char*)0,""); 
    43         if(ierr) _error_("Could not initialize Petsc");
    44 #else
    45 #ifdef _HAVE_MPI_
    46         MPI_Init(&argc,&argv);
    47 #endif
    48 #endif
     47        /*Initialize environment (MPI, PETSC, MUMPS, etc ...)*/
     48        comm=EnvironmentInit(argc,argv);
    4949
    50         /*Size and rank: */
    51 #ifdef _HAVE_MPI_
    52         MPI_Comm_rank(MPI_COMM_WORLD,&my_rank); 
    53         MPI_Comm_size(MPI_COMM_WORLD,&num_procs);
    54 #endif
     50        MPI_Comm_size(comm,&num_procs);
     51        MPI_Comm_rank(comm,&my_rank);
    5552
    5653        /*First process inputs*/
     
    7673                results->AddObject(new GenericExternalResult<double*>(results->Size()+1,1,error,ninterp,1,1,0));
    7774                for(int i=0;i<results->Size();i++){
    78                         ExternalResult* result=(ExternalResult*)results->GetObjectByOffset(i);
     75                        ExternalResult* result=dynamic_cast<ExternalResult*>(results->GetObjectByOffset(i));
    7976                        result->WriteData(output_fid,1);
    8077                }
     
    10198        delete results;
    10299
    103 #ifdef _HAVE_PETSC_
    104         _pprintLine_("closing MPI and Petsc");
    105         PetscFinalize();
    106 #else
    107 #ifdef _HAVE_MPI_
    108         _pprintLine_("closing MPI and Petsc");
    109         MPI_Finalize();
    110 #endif
    111 #endif
     100        /*Finalize environment:*/
     101        EnvironmentFinalize();
    112102
    113         /*end module: */
    114         ISSMEND();
     103        /*Finalize exception trapping: */
     104        ExceptionTrapEnd();
    115105
    116106        return 0; //unix success return;
     
    166156        Option  *option   = NULL;
    167157
    168         int dummy,M,N;
     158        int      M,N;
    169159        IoModel* iomodel = new IoModel();
    170160        iomodel->fid=fid;
  • issm/trunk/src/c/solutions/objectivefunction.cpp

    r13395 r13975  
    2222IssmDouble objectivefunction(IssmDouble search_scalar,OptArgs* optargs){
    2323
    24         int i; 
    25        
    2624        /*output: */
    2725        IssmDouble J;
    28        
     26
    2927        /*parameters: */
    3028        int        solution_type,analysis_type;
     
    7068
    7169        /*Compute misfit for this velocity field.*/
    72         CostFunctionx(&J, femmodel->elements,femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
     70        femmodel->CostFunctionx(&J);
    7371
    7472        /*Free ressources:*/
  • issm/trunk/src/c/solutions/prognostic_core.cpp

    r13395 r13975  
    1717        bool save_results;
    1818        bool issmbgradients,ispdd,isdelta18o;
     19        int  solution_type;
     20        int  *requested_outputs = NULL;
     21        int  numoutputs=0;
    1922
    2023        /*activate formulation: */
    2124        femmodel->SetCurrentConfiguration(PrognosticAnalysisEnum);
    22        
     25
    2326        /*recover parameters: */
    2427        femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
     
    2629        femmodel->parameters->FindParam(&ispdd,SurfaceforcingsIspddEnum);
    2730        femmodel->parameters->FindParam(&isdelta18o,SurfaceforcingsIsdelta18oEnum);
     31        femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
     32        femmodel->parameters->FindParam(&numoutputs,PrognosticNumRequestedOutputsEnum);
     33        if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,PrognosticRequestedOutputsEnum);
    2834
    2935        if(issmbgradients){
     
    4147        if(VerboseSolution()) _pprintLine_("   call computational core");
    4248        solver_linear(femmodel);
    43        
     49
    4450        if(save_results){
    4551                if(VerboseSolution()) _pprintLine_("   saving results");
    4652                InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,ThicknessEnum);
     53                femmodel->RequestedOutputsx(requested_outputs,numoutputs);
    4754        }
     55
     56        if(solution_type==PrognosticSolutionEnum)femmodel->RequestedDependentsx();
     57
     58        /*Free ressources:*/
     59        xDelete<int>(requested_outputs);
    4860}
  • issm/trunk/src/c/solutions/solutions.h

    r13395 r13975  
    88#include "../classes/objects/objects.h"
    99#include "../io/io.h"
     10#include "../toolkits/toolkits.h"
    1011
    1112struct OptArgs;
     
    3031void steadystate_core(FemModel* femmodel);
    3132void transient_core(FemModel* femmodel);
     33void dakota_core(FemModel* femmodel);
     34void ad_core(FemModel* femmodel);
    3235IssmDouble objectivefunction(IssmDouble search_scalar,OptArgs* optargs);
    3336
     
    4548void controlrestart(FemModel* femmodel,IssmDouble* J);
    4649void ResetBoundaryConditions(FemModel* femmodel, int analysis_type);
     50COMM EnvironmentInit(int argc,char** argv);
     51void EnvironmentFinalize(void);
     52int  DakotaSpawnCore(double* responses, int numresponses, double* variables, char** variables_descriptors,int numvariables, void* femmodel,int counter);
     53void PrintBanner(void);
    4754
    4855//solution configuration
    4956void AnalysisConfiguration(int** panalyses,int* pnumanalyses, int solutiontype);
    5057void CorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype);
     58void WrapperCorePointerFromSolutionEnum(void (**psolutioncore)(FemModel*),Parameters* parameters,int solutiontype,bool nodakotacore=false);
    5159void AdjointCorePointerFromSolutionEnum(void (**padjointcore)(FemModel*),int solutiontype);
    5260
  • issm/trunk/src/c/solutions/steadystate_core.cpp

    r13395 r13975  
    2929        int  numoutputs         = 0;
    3030        int  *requested_outputs = NULL;
    31        
     31
    3232        /* recover parameters:*/
    3333        femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
     
    4242
    4343        for(;;){
    44        
     44
    4545                if(VerboseSolution()) _pprintLine_("   computing temperature and velocity for step: " << step);
    4646                #ifdef _HAVE_THERMAL_
     
    6666                        break;
    6767                }
    68                
     68
    6969                if(VerboseSolution()) _pprintLine_("   saving velocity, temperature and pressure to check for convergence at next step");
    7070                InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,VxEnum,VxPicardEnum);
     
    7373                InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,PressureEnum,PressurePicardEnum);
    7474                InputDuplicatex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,TemperatureEnum,TemperatureOldEnum);
    75                
     75
    7676                //increase counter
    7777                step++;
    7878        }
    79        
     79
    8080        if(save_results){
    8181                if(VerboseSolution()) _pprintLine_("   saving results");
     
    8989                if(isenthalpy) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,EnthalpyEnum);
    9090                if(!isenthalpy) InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,BasalforcingsMeltingRateEnum);
    91                 RequestedOutputsx(femmodel->results,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,requested_outputs,numoutputs);
     91                femmodel->RequestedOutputsx(requested_outputs,numoutputs);
    9292        }
    9393
  • issm/trunk/src/c/solutions/steadystateconvergence.cpp

    r13395 r13975  
    1818
    1919bool steadystateconvergence(FemModel* femmodel){
    20        
     20
    2121        /*output: */
    2222        bool converged=false;
     
    3232        /*retrieve parameters: */
    3333        femmodel->parameters->FindParam(&convergencecriterionvalue[0],SteadystateReltolEnum);
    34        
     34
    3535        /*figure out convergence at the input level, because we don't have the solution vectors!: */
    3636        velocity_converged=InputConvergencex(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,&velocityenums[0],8,&convergencecriterion[0],&convergencecriterionvalue[0],1);
  • issm/trunk/src/c/solutions/surfaceslope_core.cpp

    r13395 r13975  
    2626        femmodel->SetCurrentConfiguration(SurfaceSlopeAnalysisEnum,SurfaceSlopeYAnalysisEnum);
    2727        solver_linear(femmodel);
    28        
     28
    2929        if(save_results){
    3030                if(VerboseSolution()) _pprintLine_("saving results:");
  • issm/trunk/src/c/solutions/thermal_core.cpp

    r13395 r13975  
    1616
    1717        /*intermediary*/
    18         IssmDouble melting_offset;
    1918        bool   save_results;
    2019        bool   dakota_analysis  = false;
  • issm/trunk/src/c/solutions/transient_core.cpp

    r13395 r13975  
    3131        int    numoutputs         = 0;
    3232        int    *requested_outputs = NULL;
    33        
     33
    3434        /*intermediary: */
    3535        int    step;
     
    7878                /*Increment*/
    7979                if(time_adapt){
    80                         TimeAdaptx(&dt,femmodel->elements, femmodel->nodes,femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
     80                        femmodel->TimeAdaptx(&dt);
    8181                        if(time+dt>finaltime) dt=finaltime-time;
    8282                        femmodel->parameters->SetParam(dt,TimesteppingTimeStepEnum);
     
    107107                        #endif
    108108                }
    109                
     109
    110110                if(isdiagnostic){
    111111                        if(VerboseSolution()) _pprintLine_("   computing new velocity");
     
    121121                        prognostic_core(femmodel);
    122122                        if(VerboseSolution()) _pprintLine_("   updating vertices positions");
    123                         UpdateVertexPositionsx(femmodel->elements, femmodel->nodes,femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
     123                        femmodel->UpdateVertexPositionsx();
    124124                }
    125125
     
    140140                        InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,SurfaceforcingsMassBalanceEnum);
    141141                        InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,MaskElementonfloatingiceEnum);
    142                         RequestedOutputsx(femmodel->results,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,requested_outputs,numoutputs);
     142                        femmodel->RequestedOutputsx(requested_outputs,numoutputs);
    143143
    144144                        if(isdelta18o){
     
    152152        }
    153153
    154         RequestedDependentsx(femmodel->results,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
    155        
     154        femmodel->RequestedDependentsx();
     155
    156156        /*Free ressources:*/
    157157        xDelete<int>(requested_outputs);
  • issm/trunk/src/c/solvers/solver_adjoint_linear.cpp

    r13395 r13975  
    2424        /*Recover parameters: */
    2525        femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
    26         UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
     26        femmodel->UpdateConstraintsx();
    2727
    28         SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
     28        femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
    2929        CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
    3030        Reduceloadx(pf, Kfs, ys,true); xdelete(&Kfs); //true means spc = 0
  • issm/trunk/src/c/solvers/solver_linear.cpp

    r13395 r13975  
    2222        /*Recover parameters: */
    2323        femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
    24         UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
     24        femmodel->UpdateConstraintsx();
    2525
    26         SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
     26        femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
    2727        CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
    2828        Reduceloadx(pf, Kfs, ys); xdelete(&Kfs);
  • issm/trunk/src/c/solvers/solver_newton.cpp

    r13395 r13975  
    1515        /*intermediary: */
    1616        bool   converged;
    17         int    num_unstable_constraints;
    1817        int    count;
    1918        IssmDouble kmax;
     
    3837        femmodel->parameters->FindParam(&max_nonlinear_iterations,DiagnosticMaxiterEnum);
    3938        femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
    40         UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
     39        femmodel->UpdateConstraintsx();
    4140
    4241        count=1;
     
    5756
    5857                /*Solver forward model*/
    59                 SystemMatricesx(&Kff,&Kfs,&pf,&df,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
     58                femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
    6059                CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
    6160                Reduceloadx(pf,Kfs,ys);xdelete(&Kfs);
     
    8483
    8584                /*Prepare next iteration using Newton's method*/
    86                 SystemMatricesx(&Kff,&Kfs,&pf,NULL,&kmax,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
     85                femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
    8786                CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
    8887                Reduceloadx(pf,Kfs,ys);   xdelete(&Kfs);
     
    9190                pJf->Scale(-1.0); pJf->AXPY(pf,+1.0);     xdelete(&pf);
    9291
    93                 CreateJacobianMatrixx(&Jff,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,kmax);
     92                femmodel->CreateJacobianMatrixx(&Jff,kmax);
    9493                Solverx(&duf,Jff,pJf,NULL,NULL,femmodel->parameters); xdelete(&Jff); xdelete(&pJf);
    9594                uf->AXPY(duf, 1.0); xdelete(&duf);
  • issm/trunk/src/c/solvers/solver_nonlinear.cpp

    r13395 r13975  
    2323        Vector<IssmDouble>* df  = NULL;
    2424        Vector<IssmDouble>* ys  = NULL;
    25        
    26         Loads* loads=NULL;
     25
     26        Loads* savedloads=NULL;
    2727        bool converged;
    2828        int constraints_converged;
     
    3333        int min_mechanical_constraints;
    3434        int max_nonlinear_iterations;
    35         int  configuration_type;
     35        int configuration_type;
    3636
    3737        /*Recover parameters: */
     
    3939        femmodel->parameters->FindParam(&max_nonlinear_iterations,DiagnosticMaxiterEnum);
    4040        femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
    41         UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
     41        femmodel->UpdateConstraintsx();
    4242
    4343        /*Were loads requested as output? : */
    44         if(conserve_loads) loads=(Loads*)femmodel->loads->Copy(); //protect loads from being modified by the solution
    45         else               loads=(Loads*)femmodel->loads;         //modify loads  in this solution
     44        if(conserve_loads){
     45                savedloads = static_cast<Loads*>(femmodel->loads->Copy());
     46        }
    4647
    4748        count=1;
     
    4950
    5051        /*Start non-linear iteration using input velocity: */
    51         GetSolutionFromInputsx(&ug, femmodel->elements, femmodel->nodes, femmodel->vertices, loads, femmodel->materials, femmodel->parameters);
     52        GetSolutionFromInputsx(&ug, femmodel->elements, femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
    5253        Reducevectorgtofx(&uf, ug, femmodel->nodes,femmodel->parameters);
    5354
     
    6263                xdelete(&old_uf);old_uf=uf;
    6364
    64                 SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,loads,femmodel->materials,femmodel->parameters);
     65                femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
    6566                CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
    6667                Reduceloadx(pf, Kfs, ys); xdelete(&Kfs);
     
    7273                InputUpdateFromSolutionx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug);
    7374
    74                 ConstraintsStatex(&constraints_converged, &num_unstable_constraints, femmodel->elements,femmodel->nodes,femmodel->vertices,loads,femmodel->materials,femmodel->parameters);
     75                ConstraintsStatex(&constraints_converged, &num_unstable_constraints, femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
    7576                if(VerboseConvergence()) _pprintLine_("   number of unstable constraints: " << num_unstable_constraints);
    7677
     
    108109
    109110        /*clean-up*/
    110         if(conserve_loads) delete loads;
     111        if(conserve_loads){
     112                delete femmodel->loads;
     113                femmodel->loads=savedloads;
     114        }
    111115        xdelete(&uf);
    112116        xdelete(&ug);
  • issm/trunk/src/c/solvers/solver_stokescoupling_nonlinear.cpp

    r13395 r13975  
    1414
    1515        /*intermediary: */
    16         Matrix<IssmDouble>*  Kff_horiz = NULL;
    17         Matrix<IssmDouble>* Kfs_horiz   = NULL;
    18         Vector<IssmDouble>*  ug_horiz  = NULL;
    19         Vector<IssmDouble>*  uf_horiz  = NULL;
    20         Vector<IssmDouble>old_uf_horiz = NULL;
    21         Vector<IssmDouble>*  pf_horiz  = NULL;
    22         Vector<IssmDouble>*  df_horiz  = NULL;
    23         Matrix<IssmDouble>*  Kff_vert  = NULL;
    24         Matrix<IssmDouble>*  Kfs_vert  = NULL;
    25         Vector<IssmDouble>*  ug_vert   = NULL;
    26         Vector<IssmDouble>*  uf_vert   = NULL;
    27         Vector<IssmDouble>*  pf_vert   = NULL;
    28         Vector<IssmDouble>*  df_vert   = NULL;
    29         Vector<IssmDouble>*  ys   = NULL;
     16        Matrix<IssmDouble> *Kff_horiz    = NULL;
     17        Matrix<IssmDouble> *Kfs_horiz    = NULL;
     18        Vector<IssmDouble> *ug_horiz     = NULL;
     19        Vector<IssmDouble> *uf_horiz     = NULL;
     20        Vector<IssmDouble> *old_uf_horiz = NULL;
     21        Vector<IssmDouble> *pf_horiz     = NULL;
     22        Vector<IssmDouble> *df_horiz     = NULL;
     23        Matrix<IssmDouble> *Kff_vert     = NULL;
     24        Matrix<IssmDouble> *Kfs_vert     = NULL;
     25        Vector<IssmDouble> *ug_vert      = NULL;
     26        Vector<IssmDouble> *uf_vert      = NULL;
     27        Vector<IssmDouble> *pf_vert      = NULL;
     28        Vector<IssmDouble> *df_vert      = NULL;
     29        Vector<IssmDouble> *ys           = NULL;
    3030        bool converged;
    31         int  constraints_converged;
    32         int  num_unstable_constraints;
    3331        int  count;
    3432
     
    4139        femmodel->parameters->FindParam(&min_mechanical_constraints,DiagnosticRiftPenaltyThresholdEnum);
    4240        femmodel->parameters->FindParam(&max_nonlinear_iterations,DiagnosticMaxiterEnum);
    43         UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
    44        
     41        femmodel->UpdateConstraintsx();
     42
    4543        count=1;
    4644        converged=false;
     
    5654                femmodel->SetCurrentConfiguration(DiagnosticHorizAnalysisEnum);
    5755                femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
    58        
     56
    5957                //Update once again the solution to make sure that vx and vxold are similar (for next step in transient or steadystate)
    6058                InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug_horiz);
     
    6563
    6664                /*solve: */
    67                 SystemMatricesx(&Kff_horiz, &Kfs_horiz, &pf_horiz, &df_horiz, NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
     65                femmodel->SystemMatricesx(&Kff_horiz, &Kfs_horiz, &pf_horiz, &df_horiz, NULL);
    6866                CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
    6967                Reduceloadx(pf_horiz, Kfs_horiz, ys); xdelete(&Kfs_horiz);
     
    7775                femmodel->SetCurrentConfiguration(DiagnosticVertAnalysisEnum);
    7876                femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
    79                
     77
    8078                /*solve: */
    81                 SystemMatricesx(&Kff_vert, &Kfs_vert, &pf_vert,  &df_vert,NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
     79                femmodel->SystemMatricesx(&Kff_vert, &Kfs_vert, &pf_vert,  &df_vert,NULL);
    8280                CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
    8381                Reduceloadx(pf_vert, Kfs_vert, ys); xdelete(&Kfs_vert);
  • issm/trunk/src/c/solvers/solver_thermal_nonlinear.cpp

    r13395 r13975  
    3636        int  configuration_type;
    3737
    38 
    3938        /*Recover parameters: */
    4039        kflag=1; pflag=1;
     
    5049        InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,true,ResetPenaltiesEnum);
    5150        InputUpdateFromConstantx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,false,ConvergedEnum);
    52         UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);
     51        femmodel->UpdateConstraintsx();
    5352
    5453        for(;;){
    5554
    56                 SystemMatricesx(&Kff, &Kfs, &pf,&df, &melting_offset,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
     55                femmodel->SystemMatricesx(&Kff, &Kfs, &pf,&df, &melting_offset);
    5756                CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
    5857                Reduceloadx(pf, Kfs, ys); xdelete(&Kfs); xdelete(&tf);
     
    7675
    7776                InputUpdateFromConstantx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,converged,ConvergedEnum);
    78                
     77
    7978                if(converged)break;
    8079        }
  • issm/trunk/src/c/toolkits/issm/SeqMat.h

    r13395 r13975  
    3030
    3131        public:
    32        
     32
    3333                int M,N;
    3434                doubletype* matrix;  /*here, doubletype is either IssmDouble or IssmPDouble*/
     
    6161                }
    6262                /*}}}*/
     63                /*FUNCTION SeqMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){{{*/
     64                SeqMat(int m,int n,int pM,int pN,int* d_nnz,int* o_nnz){
     65
     66                        this->M=pM;
     67                        this->N=pN;
     68                        this->matrix=NULL;
     69                        if(pM*pN) this->matrix=xNewZeroInit<doubletype>(pM*pN);
     70                }
     71                /*}}}*/
    6372                /*FUNCTION SeqMat(doubletype* serial_mat,int M,int N,doubletype sparsity){{{*/
    6473                SeqMat(doubletype* serial_mat,int pM,int pN,doubletype sparsity){
    65 
    66                         int i,j;
    6774
    6875                        this->M=pM;
  • issm/trunk/src/c/toolkits/issm/SeqVec.h

    r13395 r13975  
    2929
    3030        public:
    31        
     31
    3232                doubletype* vector;
    3333                int M;
     
    4949                }
    5050                /*}}}*/
     51                /*FUNCTION SeqVec(int m,int M){{{*/
     52                SeqVec(int pm,int pM){
     53
     54                        this->M=pM;
     55                        this->vector=NULL;
     56                        if(this->M) this->vector=xNewZeroInit<doubletype>(pM);
     57                }
     58                /*}}}*/
    5159                /*FUNCTION SeqVec(int M,bool fromlocalsize){{{*/
    5260                SeqVec(int pM,bool fromlocalsize){
     
    5967                /*FUNCTION SeqVec(doubletype* serial_vec,int M){{{*/
    6068                SeqVec(doubletype* buffer,int pM){
    61 
    62                         int i,j;
    6369
    6470                        this->M=pM;
  • issm/trunk/src/c/toolkits/mpi/mpiincludes.h

    r1 r13975  
    77
    88/*MPI includes: */
    9 #include "mpi.h"
     9#include <mpi.h>
    1010
    1111/*Patches: */
  • issm/trunk/src/c/toolkits/mpi/patches/DetermineLocalSize.cpp

    r12706 r13975  
    66#include <math.h>
    77#include "../../../shared/shared.h"
     8#include "../../../include/types.h"
    89
    9 int DetermineLocalSize(int global_size){
     10int DetermineLocalSize(int global_size,COMM comm){
    1011
    1112        /*output: */
     
    1819
    1920        /*from MPI: */
    20         extern int num_procs;
    21         extern int my_rank;
    22        
     21        int num_procs;
     22        int my_rank;
     23
     24        /*recover my_rank*/
     25        MPI_Comm_rank(comm,&my_rank);
     26        MPI_Comm_size(comm,&num_procs);
     27
    2328        /*We are  not bound by any library, just use what seems most logical*/
    2429        num_local_rows=xNew<int>(num_procs);   
     
    3035                num_local_rows[i]=(int)floor((double)global_size/(double)num_procs);
    3136        }
    32        
     37
    3338        /*There may be some rows left. Distribute evenly.*/
    3439        row_rest=global_size - num_procs*(int)floor((double)global_size/(double)num_procs);
     
    3742        }
    3843        local_size=num_local_rows[my_rank];
    39        
     44
    4045        /*free ressources: */
    4146        xDelete<int>(num_local_rows);
  • issm/trunk/src/c/toolkits/mpi/patches/mpipatches.h

    r11995 r13975  
    33 */
    44
    5 
    65#ifndef MPI_PATCHES_H_
    76#define MPI_PATCHES_H_
    87
     8#include "../../../include/types.h"
    99
    10 int MPI_Boundariesfromrange(int* plower_row, int* pupper_row,int range);
    11 int MPI_Lowerrow(int n);
    12 int MPI_Upperrow(int n);
    13 int DetermineLocalSize(int global_size);
    14 
    15 
    16 
     10int DetermineLocalSize(int global_size,COMM comm);
    1711
    1812#endif
  • issm/trunk/src/c/toolkits/petsc/objects/PetscMat.cpp

    r13395 r13975  
    3131PetscMat::PetscMat(int M,int N){
    3232
    33         this->matrix=NewMat(M,N);
     33        this->matrix=NewMat(M,N,IssmComm::GetComm());
    3434}
    3535/*}}}*/
     
    3737PetscMat::PetscMat(int M,int N, IssmDouble sparsity){
    3838
    39         this->matrix=NewMat(M,N,sparsity);
     39        this->matrix=NewMat(M,N,sparsity,IssmComm::GetComm());
    4040}
    4141/*}}}*/
    42 /*FUNCTION PetscMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity){{{*/
     42/*FUNCTION PetscMat::PetscMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){{{*/
     43PetscMat::PetscMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz){
     44
     45        MatCreate(IssmComm::GetComm(),&this->matrix);
     46        MatSetSizes(this->matrix,m,n,M,N);
     47        MatSetFromOptions(this->matrix);
     48        MatMPIAIJSetPreallocation(this->matrix,0,d_nnz,0,o_nnz);
     49        //MatSetOption(this->matrix,MAT_NEW_NONZERO_ALLOCATION_ERR,PETSC_FALSE);
     50
     51}
     52/*}}}*/
     53/*FUNCTION PetscMat::PetscMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity){{{*/
    4354PetscMat::PetscMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity){
    4455
     
    4657        int* idxm=NULL;
    4758        int* idxn=NULL;
    48        
     59
    4960        if(M)idxm=xNew<int>(M);
    5061        if(N)idxn=xNew<int>(N);
     
    5364        for(i=0;i<N;i++)idxn[i]=i;
    5465
    55 
    56         this->matrix=NewMat(M,N,sparsity);
     66        this->matrix=NewMat(M,N,sparsity,IssmComm::GetComm());
    5767        MatSetValues(this->matrix,M,idxm,N,idxn,serial_mat,INSERT_VALUES);
    5868        MatAssemblyBegin(this->matrix,MAT_FINAL_ASSEMBLY);
     
    6676/*FUNCTION PetscMat::PetscMat(int M,int N, int connectivity, int numberofdofspernode){{{*/
    6777PetscMat::PetscMat(int M,int N, int connectivity,int numberofdofspernode){
    68        
    69         this->matrix=NewMat(M,N,connectivity,numberofdofspernode);
     78
     79        this->matrix=NewMat(M,N,connectivity,numberofdofspernode,IssmComm::GetComm());
    7080
    7181}
     
    7888
    7989/*PetscMat specific routines: */
     90/*FUNCTION PetscMat::AllocationInfo{{{*/
     91void PetscMat::AllocationInfo(void){
     92
     93        MatInfo info;
     94        MatGetInfo(this->matrix,MAT_GLOBAL_SUM,&info);
     95        _pprintLine_("=========================== Stiffness matrix allocation info ===========================");
     96        _pprintLine_("");
     97        _pprintLine_(" nz_allocated: "<<info.nz_allocated);
     98        _pprintLine_(" nz_used     : "<<info.nz_used);
     99        _pprintLine_(" nz_unneeded : "<<info.nz_unneeded<<" ("<<double(info.nz_unneeded)/double(info.nz_allocated)*100.<<"%)");
     100        _pprintLine_("");
     101        _pprintLine_("========================================================================================");
     102}
     103/*}}}*/
    80104/*FUNCTION PetscMat::Echo{{{*/
    81105void PetscMat::Echo(void){
     
    90114        MatAssemblyBegin(this->matrix,MAT_FINAL_ASSEMBLY);
    91115        MatAssemblyEnd(this->matrix,MAT_FINAL_ASSEMBLY);
    92         #if _PETSC_MAJOR_ == 2
    93                 MatCompress(this->matrix);
    94         #endif
    95116
    96117}
     
    99120IssmDouble PetscMat::Norm(NormMode mode){
    100121
    101 
    102122        IssmDouble norm=0;
    103123        _assert_(this->matrix);
    104124        MatNorm(this->matrix,ISSMToPetscNormMode(mode),&norm);
    105        
     125
    106126        return norm;
    107127
     
    128148        _assert_(this->matrix);
    129149        _assert_(X->vector);
    130         MatMultPatch(this->matrix,X->vector,AX->vector);
     150        MatMultPatch(this->matrix,X->vector,AX->vector,IssmComm::GetComm());
    131151
    132152}
     
    135155PetscMat* PetscMat::Duplicate(void){
    136156
    137         PetscMat* output=NULL;
    138 
    139         output=new PetscMat();
     157        PetscMat* output=new PetscMat();
    140158        _assert_(this->matrix);
    141159        MatDuplicate(this->matrix,MAT_COPY_VALUES,&output->matrix);
     
    150168         IssmDouble* output=NULL;
    151169
    152          MatToSerial(&output,this->matrix);
     170         MatToSerial(&output,this->matrix,IssmComm::GetComm());
    153171         return output;
    154172
  • issm/trunk/src/c/toolkits/petsc/objects/PetscMat.h

    r13395 r13975  
    3131                #endif
    3232
    33                 /*PetscMat constructors, destructors {{{*/
     33                /*PetscMat constructors, destructors*/
    3434                PetscMat();
    3535                PetscMat(int M,int N);
    3636                PetscMat(int M,int N,IssmDouble sparsity);
     37                PetscMat(int m,int n,int M,int N,int* d_nnz,int* o_nnz);
    3738                PetscMat(IssmDouble* serial_mat,int M,int N,IssmDouble sparsity);
    3839                PetscMat(int M,int N,int connectivity,int numberofdofspernode);
    3940                ~PetscMat();
    40                 /*}}}*/
    41                 /*PetscMat specific routines {{{*/
     41
     42                /*PetscMat specific routines*/
     43                void AllocationInfo(void);
    4244                void Echo(void);
    4345                void Assemble(void);
     
    5052                void SetValues(int m,int* idxm,int n,int* idxn,IssmDouble* values,InsMode mode);
    5153                void Convert(MatrixType type);
    52                 /*}}}*/
     54};
    5355
    54 };
    55                
    5656#endif //#ifndef _PETSCMAT_H_
  • issm/trunk/src/c/toolkits/petsc/objects/PetscVec.cpp

    r13395 r13975  
    2929/*FUNCTION PetscVec::PetscVec(int M,bool fromlocalsize){{{*/
    3030PetscVec::PetscVec(int M,bool fromlocalsize){
    31        
    32         this->vector=NewVec(M,fromlocalsize);
     31
     32        this->vector=NewVec(M,IssmComm::GetComm(),fromlocalsize);
     33
     34}
     35/*}}}*/
     36/*FUNCTION PetscVec::PetscVec(int m,int M){{{*/
     37PetscVec::PetscVec(int m,int M){
     38
     39        VecCreate(IssmComm::GetComm(),&this->vector);
     40        VecSetSizes(this->vector,m,M);
     41        VecSetFromOptions(this->vector);
     42        VecSet(this->vector,0.0);
    3343
    3444}
     
    3848
    3949        if(petsc_vec==NULL){
    40                 this->vector=NewVec(0);
     50                this->vector=NewVec(0,IssmComm::GetComm());
    4151        }
    4252        else{
     
    5565        for(int i=0;i<M;i++) idxm[i]=i;
    5666
    57         this->vector=NewVec(M);
     67        this->vector=NewVec(M,IssmComm::GetComm());
    5868        VecSetValues(this->vector,M,idxm,serial_vec,INSERT_VALUES);
    5969        VecAssemblyBegin(this->vector);
     
    7989/*FUNCTION PetscVec::Assemble{{{*/
    8090void PetscVec::Assemble(void){
    81                
     91
    8292        _assert_(this->vector);
    8393        VecAssemblyBegin(this->vector);
     
    8898/*FUNCTION PetscVec::SetValues{{{*/
    8999void PetscVec::SetValues(int ssize, int* list, IssmDouble* values, InsMode mode){
    90        
     100
    91101        _assert_(this->vector);
    92102        VecSetValues(this->vector,ssize,list,values,ISSMToPetscInsertMode(mode));
     
    128138/*FUNCTION PetscVec::Duplicate{{{*/
    129139PetscVec* PetscVec::Duplicate(void){
    130        
    131         PetscVec* output=NULL;
     140
    132141        _assert_(this->vector);
    133142        Vec vec_output=NULL;
    134143        VecDuplicate(this->vector,&vec_output);
    135         output=new PetscVec(vec_output);
     144        PetscVec* output=new PetscVec(vec_output);
    136145        VecFree(&vec_output);
    137146
     
    165174/*FUNCTION PetscVec::ToMPISerial{{{*/
    166175IssmDouble* PetscVec::ToMPISerial(void){
    167        
     176
    168177        IssmDouble* vec_serial=NULL;
    169         VecToMPISerial(&vec_serial, this->vector);
     178        VecToMPISerial(&vec_serial, this->vector,IssmComm::GetComm());
    170179        return vec_serial;
    171180
  • issm/trunk/src/c/toolkits/petsc/objects/PetscVec.h

    r13395 r13975  
    1919#include "../../../include/include.h"
    2020
    21 
    2221/*}}}*/
    2322
     
    3130                #endif
    3231
    33 
    34                 /*PetscVec constructors, destructors {{{*/
     32                /*PetscVec constructors, destructors*/
    3533                PetscVec();
    3634                PetscVec(int M,bool fromlocalsize=false);
     35                PetscVec(int m,int M);
    3736                PetscVec(IssmDouble* buffer, int M);
    3837                PetscVec(Vec petsc_vec);
    3938                ~PetscVec();
    40                 /*}}}*/
    41                 /*PetscVec specific routines {{{*/
     39
     40                /*PetscVec specific routines*/
    4241                void Echo(void);
    4342                void Assemble(void);
     
    5756                void PointwiseDivide(PetscVec* x,PetscVec* y);
    5857                IssmDouble Dot(PetscVec* vector);
    59                 /*}}}*/
    6058};
    6159
  • issm/trunk/src/c/toolkits/petsc/patches/GetOwnershipBoundariesFromRange.cpp

    r12706 r13975  
    33 *  lower row and upper row from a matrix a cpu owns.
    44 */
    5 
    65
    76#ifdef HAVE_CONFIG_H
     
    1413#include "../../../shared/shared.h"
    1514
    16 void GetOwnershipBoundariesFromRange(int* plower_row,int* pupper_row,int range){
     15void GetOwnershipBoundariesFromRange(int* plower_row,int* pupper_row,int range,COMM comm){
    1716
    1817        /*externals :*/
    19         extern int my_rank;
    20         extern int num_procs;
    21        
     18        int my_rank;
     19        int num_procs;
     20
     21        /*recover my_rank and num_procs:*/
     22        MPI_Comm_size(comm,&num_procs);
     23        MPI_Comm_rank(comm,&my_rank);
     24
    2225        /*output: */
    2326        int lower_row,upper_row;
    24        
    25         /*intermediary :*/
    26         int i;
    27         int* allranges=NULL;
    2827
    2928        /*Gather all range values into allranges, for all nodes*/
    30         allranges=xNew<int>(num_procs);
    31         MPI_Allgather(&range,1,MPI_INT,allranges,1,MPI_INT,MPI_COMM_WORLD);
     29        int* allranges=xNew<int>(num_procs);
     30        MPI_Allgather(&range,1,MPI_INT,allranges,1,MPI_INT,comm);
    3231
    3332        /*From all ranges, get lower row and upper row*/
    3433        lower_row=0;
    3534        upper_row=lower_row+allranges[0];
    36         for (i=1;i<=my_rank;i++){
     35        for(int i=1;i<=my_rank;i++){
    3736                lower_row=lower_row+allranges[i-1];
    3837                upper_row=upper_row+allranges[i];
  • issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscInsertMode.cpp

    r13395 r13975  
    22 * \brief: convert InsertMode from ISSM to Petsc
    33 */
    4 
    54
    65#ifdef HAVE_CONFIG_H
     
    1110
    1211/*Petsc includes: */
    13 #include "petscmat.h"
    14 #include "petscvec.h"
    15 #include "petscksp.h"
     12#include <petscmat.h>
     13#include <petscvec.h>
     14#include <petscksp.h>
    1615
    1716/*ISSM includes: */
    1817#include "../../toolkitsenums.h"
    1918#include "../../../shared/shared.h"
    20 
    2119
    2220InsertMode ISSMToPetscInsertMode(InsMode mode){
  • issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscMatrixType.cpp

    r13395 r13975  
    22 * \brief: convert MatrixType from ISSM to Petsc
    33 */
    4 
    54
    65#ifdef HAVE_CONFIG_H
     
    1110
    1211/*Petsc includes: */
    13 #include "petscmat.h"
    14 #include "petscvec.h"
    15 #include "petscksp.h"
     12#include <petscmat.h>
     13#include <petscvec.h>
     14#include <petscksp.h>
    1615
    1716/*ISSM includes: */
     
    1918#include "../../../shared/shared.h"
    2019
    21 
    22 MatType ISSMToPetscMatrixType(MatrixType type){
     20const MatType ISSMToPetscMatrixType(MatrixType type){
    2321
    2422        switch(type){
  • issm/trunk/src/c/toolkits/petsc/patches/ISSMToPetscNormMode.cpp

    r13395 r13975  
    22 * \brief: convert NormMode from ISSM to Petsc
    33 */
    4 
    54
    65#ifdef HAVE_CONFIG_H
     
    1110
    1211/*Petsc includes: */
    13 #include "petscmat.h"
    14 #include "petscvec.h"
    15 #include "petscksp.h"
     12#include <petscmat.h>
     13#include <petscvec.h>
     14#include <petscksp.h>
    1615
    1716/*ISSM includes: */
    1817#include "../../toolkitsenums.h"
    1918#include "../../../shared/shared.h"
    20 
    2119
    2220NormType ISSMToPetscNormMode(NormMode mode){
  • issm/trunk/src/c/toolkits/petsc/patches/KSPFree.cpp

    r9826 r13975  
    99#endif
    1010
    11 
    1211/*Petsc includes: */
    13 #include "petscmat.h"
    14 #include "petscvec.h"
    15 #include "petscksp.h"
     12#include <petscmat.h>
     13#include <petscvec.h>
     14#include <petscksp.h>
    1615
    1716void KSPFree(KSP* pksp){
     
    2625
    2726}
    28 
  • issm/trunk/src/c/toolkits/petsc/patches/MatFree.cpp

    r9826 r13975  
    99#endif
    1010
    11 
    1211/*Petsc includes: */
    13 #include "petscmat.h"
    14 #include "petscmat.h"
    15 #include "petscksp.h"
     12#include <petscmat.h>
     13#include <petscmat.h>
     14#include <petscksp.h>
    1615
    1716void MatFree(Mat* pmat){
     
    2625
    2726}
    28 
  • issm/trunk/src/c/toolkits/petsc/patches/MatMultPatch.cpp

    r12706 r13975  
    1010
    1111/*Petsc includes: */
    12 #include "petscmat.h"
    13 #include "petscvec.h"
    14 #include "petscksp.h"
     12#include <petscmat.h>
     13#include <petscvec.h>
     14#include <petscksp.h>
    1515
    1616#include "../../../shared/shared.h"
    1717
    1818/*Function prototypes: */
    19 int MatMultCompatible(Mat A,Vec x);
    20 void VecRelocalize(Vec* outvector,Vec vector,int m);
     19int MatMultCompatible(Mat A,Vec x,COMM comm);
     20void VecRelocalize(Vec* outvector,Vec vector,int m,COMM comm);
    2121
    22 void MatMultPatch(Mat A,Vec X, Vec AX){ //same prototype as MatMult in Petsc
     22void MatMultPatch(Mat A,Vec X, Vec AX,COMM comm){ //same prototype as MatMult in Petsc
    2323
    2424        int m,n;
     
    2727        _assert_(A); _assert_(X);
    2828
    29         if (MatMultCompatible(A,X)){
     29        if (MatMultCompatible(A,X,comm)){
    3030                MatMult(A,X,AX);
    3131        }
    3232        else{
    3333                MatGetLocalSize(A,&m,&n);;
    34                 VecRelocalize(&X_rel,X,n);
     34                VecRelocalize(&X_rel,X,n,comm);
    3535                MatMult(A,X_rel,AX); ;
    3636                #if _PETSC_MAJOR_ < 3 || (_PETSC_MAJOR_ == 3 && _PETSC_MINOR_ < 2)
     
    4242}
    4343
    44 int MatMultCompatible(Mat A,Vec x){
    45        
     44int MatMultCompatible(Mat A,Vec x,COMM comm){
     45
    4646        /*error management*/
    47        
     47
    4848        int local_m,local_n;
    49         int lower_row,upper_row,range;
     49        int range;
    5050        int result=1;
    5151        int sumresult;
    52         extern int num_procs;
     52        int num_procs;
     53
     54        /*recover num_procs:*/
     55        MPI_Comm_size(comm,&num_procs);
    5356
    5457        MatGetLocalSize(A,&local_m,&local_n);;
    5558        VecGetLocalSize(x,&range);;
    56        
     59
    5760        if (local_n!=range)result=0;
    58        
     61
    5962        /*synchronize result: */
    60         MPI_Reduce (&result,&sumresult,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD );
    61         MPI_Bcast(&sumresult,1,MPI_INT,0,MPI_COMM_WORLD);               
     63        MPI_Reduce (&result,&sumresult,1,MPI_INT,MPI_SUM,0,comm );
     64        MPI_Bcast(&sumresult,1,MPI_INT,0,comm);               
    6265        if (sumresult!=num_procs){
    6366                result=0;
     
    6972}
    7073
    71 void VecRelocalize(Vec* poutvector,Vec vector,int m){
     74void VecRelocalize(Vec* poutvector,Vec vector,int m,COMM comm){
    7275
    7376        /*vector index and vector values*/
     
    7881        /*output: */
    7982        Vec outvector=NULL;
    80        
     83
    8184        /*Create outvector with local size m*/
    82         VecCreate(PETSC_COMM_WORLD,&outvector); ;
     85        VecCreate(comm,&outvector); ;
    8386        VecSetSizes(outvector,m,PETSC_DECIDE); ;
    8487        VecSetFromOptions(outvector); ;
  • issm/trunk/src/c/toolkits/petsc/patches/MatToSerial.cpp

    r12706 r13975  
    99#endif
    1010
    11 
    1211#include "../petscincludes.h"
    1312#include "../../../shared/shared.h"
    1413
    15 void MatToSerial(double** poutmatrix,Mat matrix){
     14void MatToSerial(double** poutmatrix,Mat matrix,COMM comm){
    1615
    1716        int i;
    18         extern int my_rank;
    19         extern int num_procs;
    20        
     17        int my_rank;
     18        int num_procs;
     19
    2120        /*Petsc variables*/
    2221        PetscInt lower_row,upper_row;
     
    2827        double* local_matrix=NULL; /*matrix local to each node used for temporary holding matrix values*/
    2928        int buffer[3];
    30        
     29
     30        /*recover my_rank and num_procs:*/
     31        MPI_Comm_size(comm,&num_procs);
     32        MPI_Comm_rank(comm,&my_rank);
     33
    3134        /*Output*/
    3235        double* outmatrix=NULL;
    33        
     36
    3437        /*get matrix size: */
    3538        MatGetSize(matrix,&M,&N);
     
    3942        upper_row--;
    4043        range=upper_row-lower_row+1;
    41        
     44
    4245        /*Local and global allocation*/
    4346        if (my_rank==0)outmatrix=xNew<double>(M*N);
    44        
     47
    4548        if (range){
    4649                local_matrix=xNew<double>(N*range);
    4750                idxm=xNew<int>(range); 
    4851                idxn=xNew<int>(N); 
    49          
     52
    5053                for (i=0;i<N;i++){
    5154                        *(idxn+i)=i;
     
    5457                        *(idxm+i)=lower_row+i;
    5558                }
    56        
     59
    5760                MatGetValues(matrix,range,idxm,N,idxn,local_matrix);     
    5861        }
     
    6063        /*Now each node holds its local_matrix containing range rows.
    6164         * We send these rows to the matrix on node 0*/
    62        
     65
    6366        for (i=1;i<num_procs;i++){
    6467                if (my_rank==i){
     
    6669                        buffer[1]=lower_row;
    6770                        buffer[2]=range;
    68                         MPI_Send(buffer,3,MPI_INT,0,1,MPI_COMM_WORLD);   
    69                         if (range)MPI_Send(local_matrix,N*range,MPI_DOUBLE,0,1,MPI_COMM_WORLD);
     71                        MPI_Send(buffer,3,MPI_INT,0,1,comm);   
     72                        if (range)MPI_Send(local_matrix,N*range,MPI_DOUBLE,0,1,comm);
    7073                }
    7174                if (my_rank==0){
    72                         MPI_Recv(buffer,3,MPI_INT,i,1,MPI_COMM_WORLD,&status);
    73                         if (buffer[2])MPI_Recv(outmatrix+(buffer[1]*N),N*buffer[2],MPI_DOUBLE,i,1,MPI_COMM_WORLD,&status);
     75                        MPI_Recv(buffer,3,MPI_INT,i,1,comm,&status);
     76                        if (buffer[2])MPI_Recv(outmatrix+(buffer[1]*N),N*buffer[2],MPI_DOUBLE,i,1,comm,&status);
    7477                }
    7578        }
     
    7881                memcpy(outmatrix,local_matrix,N*range*sizeof(double));
    7982        }
    80        
     83
    8184        /*Assign output pointer: */
    8285        *poutmatrix=outmatrix;
  • issm/trunk/src/c/toolkits/petsc/patches/NewMat.cpp

    r13395 r13975  
    1010
    1111/*Petsc includes: */
    12 #include "petscmat.h"
    13 #include "petscvec.h"
    14 #include "petscksp.h"
     12#include <petscmat.h>
     13#include <petscvec.h>
     14#include <petscksp.h>
    1515
    1616#include "./petscpatches.h"
     
    2121
    2222/*NewMat(int M,int N){{{*/
    23 Mat NewMat(int M,int N){
     23Mat NewMat(int M,int N,COMM comm){
    2424
    2525        /*output:*/
     
    3232
    3333        /*Determine local sizes: */
    34         m=DetermineLocalSize(M);
    35         n=DetermineLocalSize(N);
    36        
     34        m=DetermineLocalSize(M,comm);
     35        n=DetermineLocalSize(N,comm);
     36
    3737        nnz=(int)((double)M*(double)N*sparsity); //number of non zeros.
    3838        d_nz=(int)((double)nnz/(double)M/2.0); //number of non zeros per row/2
     
    4040
    4141        #if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 2
    42         MatCreateAIJ(MPI_COMM_WORLD,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix);
     42        MatCreateAIJ(comm,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix);
    4343        #else
    44         MatCreateMPIAIJ(MPI_COMM_WORLD,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix);
     44        MatCreateMPIAIJ(comm,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix);
    4545        #endif
    4646
     
    4848}
    4949/*}}}*/
    50 /*NewMat(int M,int N,double sparsity){{{*/
    51 Mat NewMat(int M,int N,double sparsity){
     50/*NewMat(int M,int N,double sparsity,COMM comm){{{*/
     51Mat NewMat(int M,int N,double sparsity,COMM comm){
    5252
    5353        /*output:*/
     
    6060
    6161        /*Determine local sizes: */
    62         m=DetermineLocalSize(M);
    63         n=DetermineLocalSize(N);
    64        
     62        m=DetermineLocalSize(M,comm);
     63        n=DetermineLocalSize(N,comm);
     64
    6565        nnz=(int)((double)M*(double)N*sparsity); //number of non zeros.
    6666        d_nz=(int)((double)nnz/(double)M/2.0); //number of non zeros per row/2
     
    6969        #if _PETSC_MAJOR_ == 3 && _PETSC_MINOR_ > 2
    7070        if(sparsity==1){
    71                 MatCreateDense(MPI_COMM_WORLD,m,n,M,N,NULL,&outmatrix);
     71                MatCreateDense(comm,m,n,M,N,NULL,&outmatrix);
    7272        }
    7373        else{
    74                 MatCreateAIJ(MPI_COMM_WORLD,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix);
     74                MatCreateAIJ(comm,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix);
    7575        }
    7676        #else
    77         MatCreateMPIAIJ(MPI_COMM_WORLD,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix);
     77        MatCreateMPIAIJ(comm,m,n,M,N,d_nz,NULL,o_nz,NULL,&outmatrix);
    7878        #endif
    7979
     
    8282/*}}}*/
    8383/*NewMat(int M,int N,int connectivity,int numberofdofspernode){{{*/
    84 Mat NewMat(int M,int N,int connectivity,int numberofdofspernode){
     84Mat NewMat(int M,int N,int connectivity,int numberofdofspernode,COMM comm){
    8585
    8686        /*output:*/
     
    9090        int    m,n;
    9191        int    d_nz,o_nz;
    92         int    nnz;
    9392
    9493        #if _PETSC_MAJOR_ >= 3
     94        #ifdef _HAVE_PETSCDEV_
     95        MatType type;
     96        #else
    9597        const MatType type;
     98        #endif
    9699        #else
    97100        MatType type;
     
    99102
    100103        /*Determine local sizes: */
    101         m=DetermineLocalSize(M);
    102         n=DetermineLocalSize(N);
     104        m=DetermineLocalSize(M,comm);
     105        n=DetermineLocalSize(N,comm);
    103106
    104107        /*Figure out number of non zeros per row: */
     
    106109        o_nz=(int)connectivity*numberofdofspernode/2;
    107110
    108         MatCreate(MPI_COMM_WORLD,&outmatrix);
     111        MatCreate(comm,&outmatrix);
    109112        MatSetSizes(outmatrix,m,n,M,N);
    110113        MatSetFromOptions(outmatrix);
     
    112115        /*preallocation  according to type: */
    113116        MatGetType(outmatrix,&type);
    114        
     117
    115118        #if _PETSC_MAJOR_ == 2
    116119        if((strcmp(type,"mpiaij")==0) || (strcmp(type,"aijmumps")==0)){
  • issm/trunk/src/c/toolkits/petsc/patches/NewVec.cpp

    r11995 r13975  
    1717#include "../../mpi/patches/mpipatches.h"
    1818
    19 Vec NewVec(int size,bool fromlocalsize){
     19Vec NewVec(int size,COMM comm,bool fromlocalsize){
    2020
    21         int ierr;
    2221        int local_size;
    2322
     
    3029        }
    3130        else{
    32                 local_size=DetermineLocalSize(size);
     31                local_size=DetermineLocalSize(size,comm);
    3332        }
    34        
    35         VecCreate(PETSC_COMM_WORLD,&vector);
    36        
     33
     34        VecCreate(comm,&vector);
     35
    3736        VecSetSizes(vector,local_size,PETSC_DECIDE);
    3837        VecSetFromOptions(vector);
  • issm/trunk/src/c/toolkits/petsc/patches/PetscMatrixToDoubleMatrix.cpp

    r12706 r13975  
    22 * \brief: convert a sparse or dense Petsc matrix into a matlab matrix
    33 */
    4 
    54
    65#ifdef HAVE_CONFIG_H
     
    1312
    1413/*Petsc includes: */
    15 #include "petscmat.h"
    16 #include "petscvec.h"
    17 #include "petscksp.h"
     14#include <petscmat.h>
     15#include <petscvec.h>
     16#include <petscksp.h>
    1817
    1918/*Petsc includes: */
    2019#include "../../../shared/shared.h"
    2120
    22 
    2321void PetscMatrixToDoubleMatrix(double** pmatrix, int* prows, int* pcols,Mat petsc_matrix){
    2422
    25         int i,j,k;
    26 
    2723        /*output: */
     24        int     i;
    2825        double* matrix=NULL;
    2926        int     rows,cols;
    30 
    31         /*intermediary: */
    32         int*    idxm=NULL;
    33         int*    idxn=NULL;
    3427
    3528        /*Some needed information: */
    3629        MatGetSize(petsc_matrix,&rows,&cols);
    3730
    38         idxm=xNew<int>(rows);
    39         idxn=xNew<int>(cols);
     31        int* idxm=xNew<int>(rows);
     32        int* idxn=xNew<int>(cols);
    4033
    4134        for(i=0;i<rows;i++)idxm[i]=i;
  • issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsDetermineSolverType.cpp

    r11527 r13975  
    5353        }
    5454
    55 
    5655        #if _PETSC_MAJOR_ >= 3
    5756        PetscOptionsGetString(PETSC_NULL,"-pc_factor_mat_solver_package",&option[0],100,&flag);
     
    6160        #endif
    6261
    63        
    6462        PetscOptionsGetString(PETSC_NULL,"-issm_option_solver",&option[0],100,&flag);
    6563        if (strcmp(option,"stokes")==0){
  • issm/trunk/src/c/toolkits/petsc/patches/PetscOptionsInsertMultipleString.cpp

    r13395 r13975  
    1010
    1111/*Petsc includes: */
    12 #include "petscmat.h"
    13 #include "petscvec.h"
    14 #include "petscksp.h"
     12#include <petscmat.h>
     13#include <petscvec.h>
     14#include <petscksp.h>
    1515
    1616#include "./petscpatches.h"
     
    2020
    2121void PetscOptionsInsertMultipleString(char* options_string){
    22 
    2322
    2423        /*The list of options is going to be pairs of the type "-option option_value"*/
     
    3029        char* first=NULL;
    3130        char* second=NULL;
    32         char* final=NULL;
    3331        size_t len;
    34         int ignore_second;
    3532        int first_token=1;
    36 
    3733
    3834        PetscTokenCreate(options_string,' ',&token);
    3935        for (;;){
    40                
    4136
    4237                /*Read next tokens*/
     
    4540                }
    4641                PetscTokenFind(token,&second);
    47                
     42
    4843                if (!first){
    4944                        /*We are at the end of options*/
     
    5954                        /*Reduce first to bare option value*/
    6055                        PetscStrlen(first,&len);
    61                         while (len > 0 && (first[len-1] == ' ' || first[len-1] == 'n')) {
     56                        while (len > 0 && first[len-1] == ' ') {
    6257                                len--; first[len] = 0;
    6358                        }
     
    7065                                /*Second is another option, ignore it*/
    7166                                PetscStrlen(first,&len);
    72                                 while (len > 0 && (first[len-1] == ' ' || first[len-1] == 'n')) {
     67                                while (len > 0 && first[len-1] == ' ' ) {
    7368                                        len--; first[len] = 0;
    7469                                }
     
    8176                                /*Second is 'first' option's value*/
    8277                                PetscStrlen(second,&len);
    83                                 while (len > 0 && (second[len-1] == ' ' || second[len-1] == 'n')) {
     78                                while (len > 0 && second[len-1] == ' ') {
    8479                                        len--; second[len] = 0;
    8580                                }
  • issm/trunk/src/c/toolkits/petsc/patches/PetscVectorToDoubleVector.cpp

    r12706 r13975  
    1111
    1212/*Petsc includes: */
    13 #include "petscmat.h"
    14 #include "petscvec.h"
    15 #include "petscksp.h"
     13#include <petscmat.h>
     14#include <petscvec.h>
     15#include <petscksp.h>
    1616
    1717#include "../../../shared/shared.h"
     
    1919void PetscVectorToDoubleVector(double** pvector, int* prows, Vec petsc_vector){
    2020
    21         int     i;
    2221        int     rows;
    23         int    *idxm   = NULL;
    2422        double *vector = NULL;
    2523
     
    2826                VecGetSize(petsc_vector,&rows);
    2927                if(rows){
    30                         idxm=xNew<int>(rows);
     28                        int* idxm=xNew<int>(rows);
    3129                        vector=xNew<double>(rows);
    32                         for(i=0;i<rows;i++)idxm[i]=i;
     30                        for(int i=0;i<rows;i++)idxm[i]=i;
    3331                        VecGetValues(petsc_vector,rows,idxm,vector);
    3432                        xDelete<int>(idxm);
  • issm/trunk/src/c/toolkits/petsc/patches/SolverEnum.h

    r9291 r13975  
    1515} EXTERNALPACKAGES;
    1616
    17 
    1817#endif //ifndef _SOLVERENUM_H_
    19 
  • issm/trunk/src/c/toolkits/petsc/patches/VecDuplicatePatch.cpp

    r9320 r13975  
    99#endif
    1010
    11 
    1211/*Petsc includes: */
    13 #include "petscmat.h"
    14 #include "petscvec.h"
    15 #include "petscksp.h"
     12#include <petscmat.h>
     13#include <petscvec.h>
     14#include <petscksp.h>
    1615
    1716void VecDuplicatePatch(Vec* output, Vec input){
  • issm/trunk/src/c/toolkits/petsc/patches/VecFree.cpp

    r9826 r13975  
    99#endif
    1010
    11 
    1211/*Petsc includes: */
    13 #include "petscmat.h"
    14 #include "petscvec.h"
    15 #include "petscksp.h"
     12#include <petscmat.h>
     13#include <petscvec.h>
     14#include <petscksp.h>
    1615
    1716void VecFree(Vec* pvec){
     
    2524
    2625}
    27 
  • issm/trunk/src/c/toolkits/petsc/patches/VecMerge.cpp

    r13395 r13975  
    1010
    1111/*Petsc includes: */
    12 #include "petscmat.h"
    13 #include "petscvec.h"
    14 #include "petscksp.h"
     12#include <petscmat.h>
     13#include <petscvec.h>
     14#include <petscksp.h>
    1515
    1616#include "./petscpatches.h"
     
    2121void VecMerge(Vec A, Vec B, double* row_partition_vector,int row_partition_size){
    2222
    23         int i;
    24        
    2523        /*Petsc matrix*/
    2624        int lower_row,upper_row,range;
     
    2927
    3028        /*Vector sizes: */
    31         int MA,MB;
     29        int MB;
    3230
    3331        VecGetSize(B,&MB);
    3432
    3533        /*If the dimension of the partitioning vector is not the same as that of vector B, we have a problem: */
    36         if ( (row_partition_size !=MB) ){
     34        if ((row_partition_size !=MB) ){
    3735                _error_("Dimensions of partitioning vector incompatible with dimensions of input vector\n");
    3836        }
     
    4745                idxm=xNew<int>(range);
    4846                values=xNew<double>(range);
    49                 for (i=0;i<range;i++){
    50                         *(idxm+i)=lower_row+i;
     47                for(int i=0;i<range;i++){
     48                        idxm[i]=lower_row+i;
    5149                }
    5250                VecGetValues(B,range,idxm,values);
    5351                /*Now, modify idxm using the partition vector, and plug values into A*/
    54                 for (i=0;i<range;i++){
    55                         *(idxm+i)=(int)*(row_partition_vector+lower_row+i)-1; //-1 because partition vector comes from Matlab, where indices start at 1.
     52                for(int i=0;i<range;i++){
     53                        idxm[i]=int(row_partition_vector[lower_row+i])-1; //-1 because partition vector comes from Matlab, where indices start at 1.
    5654                }
    5755                VecSetValues(A,range,idxm,values,INSERT_VALUES);
    5856        }
    59        
     57
    6058        /*Assemble vector*/
    6159        VecAssemblyBegin(A);
  • issm/trunk/src/c/toolkits/petsc/patches/VecToMPISerial.cpp

    r12706 r13975  
    99#endif
    1010
    11 
    1211#include "../petscincludes.h"
    1312#include "../../../shared/shared.h"
    1413
    15 int VecToMPISerial(double** pgathered_vector, Vec vector){
    16        
     14int VecToMPISerial(double** pgathered_vector, Vec vector,COMM comm){
     15
    1716        int i;
    18         extern int num_procs;
    19         extern int my_rank;
     17        int num_procs;
     18        int my_rank;
    2019
    2120        /*Petsc*/
     
    2524        int * idxn=NULL;
    2625        int buffer[3];
    27        
     26
    2827        /*intermediary results*/
    2928        double* local_vector=NULL;
     
    3130        /*input*/
    3231        int vector_size;
    33        
     32
    3433        /*Output*/
    3534        double* gathered_vector=NULL; //Global vector holding the final assembled vector on all nodes.
     35
     36        /*recover my_rank and num_procs*/
     37        MPI_Comm_size(comm,&num_procs);
     38        MPI_Comm_rank(comm,&my_rank);
    3639
    3740        VecGetSize(vector,&vector_size);
     
    4346        /*Allocate gathered vector on all nodes .*/
    4447        gathered_vector=xNew<double>(vector_size);
    45        
     48
    4649        /*Allocate local vectors*/
    4750        VecGetOwnershipRange(vector,&lower_row,&upper_row);
     
    6669                        buffer[1]=lower_row;
    6770                        buffer[2]=range;
    68                         MPI_Send(buffer,3,MPI_INT,0,1,MPI_COMM_WORLD); 
    69                         if (range)MPI_Send(local_vector,range,MPI_DOUBLE,0,1,MPI_COMM_WORLD);
     71                        MPI_Send(buffer,3,MPI_INT,0,1,comm); 
     72                        if (range)MPI_Send(local_vector,range,MPI_DOUBLE,0,1,comm);
    7073                }
    7174                if (my_rank==0){
    72                         MPI_Recv(buffer,3,MPI_INT,i,1,MPI_COMM_WORLD,&status);
    73                         if (buffer[2])MPI_Recv(gathered_vector+buffer[1],buffer[2],MPI_DOUBLE,i,1,MPI_COMM_WORLD,&status);
     75                        MPI_Recv(buffer,3,MPI_INT,i,1,comm,&status);
     76                        if (buffer[2])MPI_Recv(gathered_vector+buffer[1],buffer[2],MPI_DOUBLE,i,1,comm,&status);
    7477                }
    7578        }
     
    8184
    8285        /*Now, broadcast gathered_vector from node 0 to other nodes: */
    83         MPI_Bcast(gathered_vector,vector_size,MPI_DOUBLE,0,MPI_COMM_WORLD);
     86        MPI_Bcast(gathered_vector,vector_size,MPI_DOUBLE,0,comm);
    8487
    8588        /*Assign output pointers: */
    8689        *pgathered_vector=gathered_vector;
    87        
     90
    8891        /*free ressources: */
    8992        xDelete<int>(idxn);
    9093        xDelete<double>(local_vector);
    91        
     94
    9295        return 1;
    9396}
  • issm/trunk/src/c/toolkits/petsc/patches/petscpatches.h

    r12330 r13975  
    66#define _PETSC_PATCHES_H_
    77
    8 #include "petscmat.h"
    9 #include "petscvec.h"
    10 #include "petscksp.h"
    11 #include "petscsys.h"
     8#include <petscmat.h>
     9#include <petscvec.h>
     10#include <petscksp.h>
     11#include <petscsys.h>
    1212
    1313#include "./SolverEnum.h"
    1414#include "../../toolkitsenums.h"
     15#include "../../../include/types.h"
    1516
    1617class Parameters;
    1718
    18 Vec NewVec(int size,bool fromlocalsize=false);
    19 Mat NewMat(int M,int N);
    20 Mat NewMat(int M,int N,double sparsity);
    21 Mat NewMat(int M,int N,int connectivity,int numberofdofspernode);
     19Vec NewVec(int size,COMM comm,bool fromlocalsize=false);
     20Mat NewMat(int M,int N,COMM comm);
     21Mat NewMat(int M,int N,double sparsity,COMM comm);
     22Mat NewMat(int M,int N,int connectivity,int numberofdofspernode, COMM comm);
    2223
    23 int VecTranspose(Vec* tvector,Vec vector);
    24 int VecToMPISerial(double** pgathered_vector, Vec vector);
    25 void GetOwnershipBoundariesFromRange(int* plower_row,int* pupper_row,int range);
     24int VecToMPISerial(double** pgathered_vector, Vec vector,COMM comm);
    2625void MatFree(Mat* pmat);
    2726void ISFree(IS* pis);
    2827void VecFree(Vec* pvec);
    2928void KSPFree(KSP* pksp);
    30 void VecPartition(Vec* poutvector,Vec vectorA, double* row_partition_vector, int row_partition_vector_size,bool kffpartitioning);
    3129int MatPartition(Mat* poutmatrix,Mat matrixA,double* row_partition_vector,int row_partition_vector_size ,
    3230                double* col_partition_vector,int col_partition_vector_size);
    33 void MatInvert(Mat* pInv, Mat Matrix);
    3431void PetscOptionsInsertMultipleString(char* options_string);
    3532void PetscOptionsDetermineSolverType(int* psolver_type);
    3633void VecMerge(Vec A, Vec B, double* row_partition_vector,int row_partition_size);
    37 void MatMultPatch(Mat A,Vec X, Vec AX);
    38 void MatToSerial(double** poutmatrix,Mat matrix);
     34void MatMultPatch(Mat A,Vec X, Vec AX,COMM comm);
     35void MatToSerial(double** poutmatrix,Mat matrix,COMM comm);
    3936void VecDuplicatePatch(Vec* output, Vec input);
    4037Vec  SerialToVec(double* vector,int vector_size);
    4138InsertMode ISSMToPetscInsertMode(InsMode mode);
    4239NormType ISSMToPetscNormMode(NormMode mode);
    43 MatType ISSMToPetscMatrixType(MatrixType type);
     40const MatType ISSMToPetscMatrixType(MatrixType type);
    4441
    4542void PetscMatrixToDoubleMatrix(double** pmatrix, int* prows, int* pcols,Mat matrix);
  • issm/trunk/src/c/toolkits/plapack/patches/CyclicalFactorization.cpp

    r12706 r13975  
    33*/
    44#include <math.h>
    5 
    65
    76#include "../../../shared/shared.h"
     
    109
    1110int CyclicalFactorization(int* pnprows,int* pnpcols,int num_procs){
    12        
     11
    1312        int nprows,npcols;
    1413        int last_diff;
     
    4039int PrimeDecomp(int** pdecomp,int* pdecomp_size,int input){
    4140
    42         int* decomp=NULL;
    4341        int prime_factor;
    4442        int i;
    4543
    46         decomp=xNew<int>(input);
     44        int* decomp=xNew<int>(input);
    4745        *decomp=input;
    4846        for (i=0;i<input;i++){
     
    6563*/
    6664int SmallestPrimeFactor(int* output,int input){
    67        
     65
    6866        int found=0;
    6967        int i;
  • issm/trunk/src/c/toolkits/plapack/patches/PlapackInvertMatrix.cpp

    r13395 r13975  
    1414
    1515void PlapackInvertMatrixLocalCleanup(PLA_Obj* pa,PLA_Template* ptempl,double** parrayA,int** pidxnA,MPI_Comm* pcomm_2d);
    16        
    17 int PlapackInvertMatrix(Mat* A,Mat* inv_A,int status,int con){
     16
     17int PlapackInvertMatrix(Mat* A,Mat* inv_A,int status,int con,COMM comm){
    1818        /*inv_A does not yet exist, inv_A was just allocated, that's all*/
    1919
    2020        /*Error management*/
    21         int i,j;
     21        int i;
    2222
    2323        /*input*/
    2424        int mA,nA;
    2525        int local_mA,local_nA;
    26         int lower_row,upper_row,range,this_range,this_lower_row;
     26        int lower_row,upper_row;
    2727        MatType type;
    28        
     28
    2929        /*Plapack: */
    3030        MPI_Datatype   datatype;
     
    3636        int nb,nb_alg;
    3737        int nprows,npcols;
    38         int initialized=0;
    3938
    4039        /*Petsc to Plapack: */
    4140        double    *arrayA=NULL;
    4241        int* idxnA=NULL;
    43         int d_nz,o_nz;
    44        
    45         /*Feedback to client*/
    46         int computation_status; 
    4742
    4843        /*Verify that A is square*/
     
    7671        if(PLA_Initialized(NULL)==TRUE)PLA_Finalize();
    7772        /* Create a 2D communicator */
    78         PLA_Comm_1D_to_2D(MPI_COMM_WORLD,nprows,npcols,&comm_2d);
     73        PLA_Comm_1D_to_2D(comm,nprows,npcols,&comm_2d);
    7974
    8075        /*Initlialize plapack: */
     
    9287        /* Set the datatype */
    9388        datatype = MPI_DOUBLE;
    94        
     89
    9590        /* Copy A into a*/
    9691        PLA_Matrix_create(datatype,mA,nA,templ,PLA_ALIGN_FIRST,PLA_ALIGN_FIRST,&a); 
     
    10095        MatGetOwnershipRange(*A,&lower_row,&upper_row);
    10196        upper_row--;
    102         range=upper_row-lower_row+1;
    10397        arrayA = xNew<double>(nA);
    10498        idxnA  = xNew<int>(nA);
     
    127121        xDelete<double>(arrayA);
    128122        xDelete<int>(idxnA);
    129        
     123
    130124        /*Finalize PLAPACK*/
    131125        PLA_Finalize();
  • issm/trunk/src/c/toolkits/plapack/patches/PlapackToPetsc.cpp

    r12706 r13975  
    66#include "../plapackincludes.h"
    77
    8 int PlapackToPetsc(Mat* A,int local_mA,int local_nA,int mA,int nA,MatType type,PLA_Obj a,PLA_Template templ,int nprows,int npcols,int nb){
     8int PlapackToPetsc(Mat* A,int local_mA,int local_nA,int mA,int nA,MatType type,PLA_Obj a,PLA_Template templ,int nprows,int npcols,int nb,COMM comm){
    99
    10        
    1110        int i;
    1211
    13         int lower_row,upper_row,range;
     12        int lower_row,upper_row;
    1413        int* row_nodes=NULL;
    1514        int* col_nodes=NULL;
     
    2221        double* local_buffer=NULL;
    2322
    24 
    2523        /*Create matrix A (right now, we just have an allocated pointer A*/
    2624        if (strcasecmp_eq(type,MATMPIAIJ)){
     
    2826                d_nz=nA/2;
    2927                o_nz=nA/2;
    30                 MatCreateMPIAIJ(MPI_COMM_WORLD,local_mA,local_nA, mA,nA,d_nz,PETSC_NULL,o_nz,PETSC_NULL,A);
     28                MatCreateMPIAIJ(comm,local_mA,local_nA, mA,nA,d_nz,PETSC_NULL,o_nz,PETSC_NULL,A);
    3129        }
    3230        else if(strcasecmp_eq(type,MATMPIDENSE)){
    33                 MatCreateMPIDense(MPI_COMM_WORLD,local_mA,local_nA, mA,nA,PETSC_NULL,A);
     31                MatCreateMPIDense(comm,local_mA,local_nA, mA,nA,PETSC_NULL,A);
    3432        }
    35        
     33
    3634        MatGetOwnershipRange(*A,&lower_row,&upper_row);
    3735        upper_row--;
    38         range=upper_row-lower_row+1;
    39        
     36
    4037        /*Build the Plapack row and column indices corresponding to the local_buffer stored in a.
    4138          We need those indices to directly plug local_buffer into the Petsc matrix A. We do not
     
    4340          problem size becomes big. We rely therefore on MatAssembly from Petsc to gather the plapack
    4441          matrix into a Petsc Matrix.*/
    45        
     42
    4643        /*Vector physically based block cyclic distribution: */
    4744        row_nodes=xNew<int>(mA);
     
    8279        /*Get local buffer: */
    8380        PLA_Obj_local_buffer(a,(void**)&local_buffer);
    84        
     81
    8582        /*Insert into invA matrix. Use col oriented insertion, for Plapack is column oriented*/
    8683        MatSetOption(*A,MAT_COLUMN_ORIENTED);
  • issm/trunk/src/c/toolkits/plapack/patches/plapackpatches.h

    r831 r13975  
    66#define _PLAPACK_PATCHES_H_
    77
    8 int PlapackInvertMatrix(Mat* A,Mat* inv_A,int status,int con);
    9 int PlapackToPetsc(Mat* A,int local_mA,int local_nA,int mA,int nA,MatType type,PLA_Obj a,PLA_Template templ,int nprows,int npcols,int nb);
     8int PlapackInvertMatrix(Mat* A,Mat* inv_A,int status,int con,COMM comm);
     9int PlapackToPetsc(Mat* A,int local_mA,int local_nA,int mA,int nA,MatType type,PLA_Obj a,PLA_Template templ,int nprows,int npcols,int nb,COMM comm);
    1010int CyclicalFactorization(int* pnprows,int* pnpcols,int num_procs);
    1111
  • issm/trunk/src/c/toolkits/plapack/plapackincludes.h

    r11995 r13975  
    1212#endif
    1313
    14 
    15 #include "PLA.h"
     14#include <PLA.h>
    1615
    1716/* missing Plapack prototypes: */
     
    2019/*our own patches: */
    2120#ifdef _HAVE_PETSC_
    22 #include "patches/petscpatches.h"
     21#include "./patches/petscpatches.h"
    2322#endif
    2423
    25 
    2624#endif
    27 
  • issm/trunk/src/c/toolkits/scalapack/FortranMapping.h

    r831 r13975  
    55 *     Description:  Fortran to C define to use Scalapack in a C program
    66 */
    7 
    87
    98/*We transform every call to Fortran functions into their real symbolic name in the Scalapack, Blacs, Lapack and Blas libraries.
     
    2221#define PDGETRF(...) pdgetrf_(__VA_ARGS__)
    2322#define PDGETRI(...) pdgetri_(__VA_ARGS__)
    24 
    2523
    2624/*Here, we clobber the fortran definition of these routines. Remember, every variable in fortran is passed by a pointer, and the
  • issm/trunk/src/c/toolkits/toolkits.h

    r12330 r13975  
    1010#else
    1111#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
    12 #endif
    13 
    14 #ifdef _HAVE_PYTHON_
    15 #include "./python/pythonincludes.h"
    1612#endif
    1713
     
    3127#include "./toolkitsenums.h"
    3228#include "./issm/issmtoolkit.h"
    33 
    3429#endif
  • issm/trunk/src/c/toolkits/triangle/triangleincludes.h

    r12330 r13975  
    1111#endif //#ifdef _C_
    1212
    13 
    1413#endif
  • issm/trunk/src/dox/issm.dox

    r12706 r13975  
    4646</th>
    4747<tr>
    48 <th  bgcolor=#FFFFFF style="text-align:left;"> C++ </th><td  bgcolor=#FFFFFF style="text-align:right;">508</td><td  bgcolor=#FFFFFF style="text-align:right;">14595</td><td  bgcolor=#FFFFFF style="text-align:right;">16762</td><td  bgcolor=#FFFFFF style="text-align:right;">56036</td><td  bgcolor=#FFFFFF style="text-align:right;">87393</td>
     48<th  bgcolor=#FFFFFF style="text-align:left;"> C++ </th><td  bgcolor=#FFFFFF style="text-align:right;">505</td><td  bgcolor=#FFFFFF style="text-align:right;">14316</td><td  bgcolor=#FFFFFF style="text-align:right;">16564</td><td  bgcolor=#FFFFFF style="text-align:right;">56522</td><td  bgcolor=#FFFFFF style="text-align:right;">87402</td>
    4949</tr>
    5050<tr>
    51 <th  bgcolor=#C6E2FF style="text-align:left;"> MATLAB </th><td  bgcolor=#C6E2FF style="text-align:right;">925</td><td  bgcolor=#C6E2FF style="text-align:right;">6851</td><td  bgcolor=#C6E2FF style="text-align:right;">13228</td><td  bgcolor=#C6E2FF style="text-align:right;">30468</td><td  bgcolor=#C6E2FF style="text-align:right;">50547</td>
     51<th  bgcolor=#C6E2FF style="text-align:left;"> MATLAB </th><td  bgcolor=#C6E2FF style="text-align:right;">913</td><td  bgcolor=#C6E2FF style="text-align:right;">6625</td><td  bgcolor=#C6E2FF style="text-align:right;">13054</td><td  bgcolor=#C6E2FF style="text-align:right;">30160</td><td  bgcolor=#C6E2FF style="text-align:right;">49839</td>
    5252</tr>
    5353<tr>
    54 <th  bgcolor=#FFFFFF style="text-align:left;"> C/C++  Header </th><td  bgcolor=#FFFFFF style="text-align:right;">378</td><td  bgcolor=#FFFFFF style="text-align:right;">2758</td><td  bgcolor=#FFFFFF style="text-align:right;">2612</td><td  bgcolor=#FFFFFF style="text-align:right;">9818</td><td  bgcolor=#FFFFFF style="text-align:right;">15188</td>
     54<th  bgcolor=#FFFFFF style="text-align:left;"> C/C++  Header </th><td  bgcolor=#FFFFFF style="text-align:right;">388</td><td  bgcolor=#FFFFFF style="text-align:right;">3069</td><td  bgcolor=#FFFFFF style="text-align:right;">2983</td><td  bgcolor=#FFFFFF style="text-align:right;">11855</td><td  bgcolor=#FFFFFF style="text-align:right;">17907</td>
    5555</tr>
    5656<tr>
    57 <th  bgcolor=#C6E2FF style="text-align:left;"> m4 </th><td  bgcolor=#C6E2FF style="text-align:right;">7</td><td  bgcolor=#C6E2FF style="text-align:right;">997</td><td  bgcolor=#C6E2FF style="text-align:right;">80</td><td  bgcolor=#C6E2FF style="text-align:right;">8259</td><td  bgcolor=#C6E2FF style="text-align:right;">9336</td>
     57<th  bgcolor=#C6E2FF style="text-align:left;"> m4 </th><td  bgcolor=#C6E2FF style="text-align:right;">6</td><td  bgcolor=#C6E2FF style="text-align:right;">1052</td><td  bgcolor=#C6E2FF style="text-align:right;">79</td><td  bgcolor=#C6E2FF style="text-align:right;">8993</td><td  bgcolor=#C6E2FF style="text-align:right;">10124</td>
    5858</tr>
    5959<tr>
    60 <th  bgcolor=#FFFFFF style="text-align:left;"> Python </th><td  bgcolor=#FFFFFF style="text-align:right;">53</td><td  bgcolor=#FFFFFF style="text-align:right;">400</td><td  bgcolor=#FFFFFF style="text-align:right;">610</td><td  bgcolor=#FFFFFF style="text-align:right;">1424</td><td  bgcolor=#FFFFFF style="text-align:right;">2434</td>
     60<th  bgcolor=#FFFFFF style="text-align:left;"> Python </th><td  bgcolor=#FFFFFF style="text-align:right;">81</td><td  bgcolor=#FFFFFF style="text-align:right;">2677</td><td  bgcolor=#FFFFFF style="text-align:right;">3936</td><td  bgcolor=#FFFFFF style="text-align:right;">5169</td><td  bgcolor=#FFFFFF style="text-align:right;">11782</td>
    6161</tr>
    6262<tr>
     
    6464</tr>
    6565<tr>
    66 <th  bgcolor=#FFFFFF style="text-align:left;"> Perl </th><td  bgcolor=#FFFFFF style="text-align:right;">3</td><td  bgcolor=#FFFFFF style="text-align:right;">21</td><td  bgcolor=#FFFFFF style="text-align:right;">23</td><td  bgcolor=#FFFFFF style="text-align:right;">240</td><td  bgcolor=#FFFFFF style="text-align:right;">284</td>
     66<th  bgcolor=#FFFFFF style="text-align:left;"> Bourne  Shell </th><td  bgcolor=#FFFFFF style="text-align:right;">5</td><td  bgcolor=#FFFFFF style="text-align:right;">58</td><td  bgcolor=#FFFFFF style="text-align:right;">81</td><td  bgcolor=#FFFFFF style="text-align:right;">268</td><td  bgcolor=#FFFFFF style="text-align:right;">407</td>
    6767</tr>
    6868<tr>
    69 <th  bgcolor=#C6E2FF style="text-align:left;"> Bourne  Shell </th><td  bgcolor=#C6E2FF style="text-align:right;">5</td><td  bgcolor=#C6E2FF style="text-align:right;">47</td><td  bgcolor=#C6E2FF style="text-align:right;">75</td><td  bgcolor=#C6E2FF style="text-align:right;">239</td><td  bgcolor=#C6E2FF style="text-align:right;">361</td>
     69<th  bgcolor=#C6E2FF style="text-align:left;"> Perl </th><td  bgcolor=#C6E2FF style="text-align:right;">3</td><td  bgcolor=#C6E2FF style="text-align:right;">21</td><td  bgcolor=#C6E2FF style="text-align:right;">23</td><td  bgcolor=#C6E2FF style="text-align:right;">240</td><td  bgcolor=#C6E2FF style="text-align:right;">284</td>
    7070</tr>
    7171<tr>
     
    7676</tr>
    7777<tr>
    78 <th  bgcolor=#FFFFFF style="text-align:left;"> SUM: </th><td  bgcolor=#FFFFFF style="text-align:right;">1890</td><td  bgcolor=#FFFFFF style="text-align:right;">25787</td><td  bgcolor=#FFFFFF style="text-align:right;">33397</td><td  bgcolor=#FFFFFF style="text-align:right;">106984</td><td  bgcolor=#FFFFFF style="text-align:right;">166168</td>
     78<th  bgcolor=#FFFFFF style="text-align:left;"> SUM: </th><td  bgcolor=#FFFFFF style="text-align:right;">1912</td><td  bgcolor=#FFFFFF style="text-align:right;">27936</td><td  bgcolor=#FFFFFF style="text-align:right;">36727</td><td  bgcolor=#FFFFFF style="text-align:right;">113707</td><td  bgcolor=#FFFFFF style="text-align:right;">178370</td>
    7979</tr>
    8080</table>
  • issm/trunk/src/m/Makefile.am

    r13395 r13975  
    33#find . -type d -exec ls -d {} \;
    44
     5if WRAPPERS
    56bin_SCRIPTS= ./qmu/*.m \
    67                                 ./qmu/setupdesign/*.m \
     
    4950                                 ./solvers/*.m \
    5051                                 ./materials/*.m
     52endif
  • issm/trunk/src/m/array/array_numel.m

    r13395 r13975  
    1717        inum=numel(varargin{iarg});
    1818    end
    19    
     19
    2020    if ~isequal(inum,1)
    2121        if isequal(anum,1)
  • issm/trunk/src/m/array/array_size.m

    r13395 r13975  
    1717        isize=size(varargin{iarg});
    1818    end
    19    
     19
    2020    if ~isequal(isize,[1 1])
    2121        if isequal(asize,[1 1])
  • issm/trunk/src/m/array/str2int.m

    r13395 r13975  
    55%  function [aint]=str2int(astr,cfl)
    66%
    7 function [aint]=str2int(astr,cfl);
     7function [aint]=str2int(astr,cfl)
    88
    99aint=[];
     
    4444
    4545end
    46 
  • issm/trunk/src/m/array/struc_desc.m

    r13395 r13975  
    2222        desc=cellstr(varargin{iarg});
    2323    end
    24    
     24
    2525    for i=1:length(desc)
    2626        sarrayoi=struc_desci(sarray,desc{i});
  • issm/trunk/src/m/boundaryconditions/SetIceSheetBC.m

    r13395 r13975  
    5858        pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
    5959        if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
    60                 md.basalforcings.geothermalflux=50*10^-3*ones(md.mesh.numberofvertices,1); %50 mW/m^2
     60                md.basalforcings.geothermalflux=50.*10^-3*ones(md.mesh.numberofvertices,1); %50 mW/m^2
    6161        end
    6262else
  • issm/trunk/src/m/boundaryconditions/SetIceShelfBC.py

    r13395 r13975  
    11import os
    22import numpy
     3from ContourToMesh import *
    34
    45def SetIceShelfBC(md,icefrontfile=''):
     
    67        SETICESHELFBC - Create the boundary conditions for diagnostic and thermal models for a  Ice Shelf with Ice Front
    78
    8            Neumann BC are used on the ice front (an ANRGUS contour around the ice front
     9           Neumann BC are used on the ice front (an ARGUS contour around the ice front
    910           must be given in input)
    1011           Dirichlet BC are used elsewhere for diagnostic
     
    2425                if not os.path.exists(icefrontfile):
    2526                        raise IOError("SetIceShelfBC error message: ice front file '%s' not found." % icefrontfile)
    26                 nodeinsideicefront=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2)
    27                 nodeonicefront=double(md.mesh.vertexonboundary and nodeinsideicefront)
     27                [nodeinsideicefront,dum]=ContourToMesh(md.mesh.elements,md.mesh.x.reshape(-1,1),md.mesh.y.reshape(-1,1),icefrontfile,'node',2)
     28                nodeonicefront=numpy.logical_and(md.mesh.vertexonboundary,nodeinsideicefront.reshape(-1)).astype(float)
    2829        else:
    29                 nodeonicefront=numpy.zeros(md.mesh.numberofvertices)
     30                nodeonicefront=numpy.zeros((md.mesh.numberofvertices))
    3031
    3132#       pos=find(md.mesh.vertexonboundary & ~nodeonicefront);
    32         pos=[i for i,(vob,noif) in enumerate(zip(md.mesh.vertexonboundary,nodeonicefront)) if vob and not noif]
    33         md.diagnostic.spcvx=float('NaN')*numpy.ones(md.mesh.numberofvertices)
    34         md.diagnostic.spcvy=float('NaN')*numpy.ones(md.mesh.numberofvertices)
    35         md.diagnostic.spcvz=float('NaN')*numpy.ones(md.mesh.numberofvertices)
     33        pos=numpy.nonzero(numpy.logical_and(md.mesh.vertexonboundary,numpy.logical_not(nodeonicefront)))[0]
     34        md.diagnostic.spcvx=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
     35        md.diagnostic.spcvy=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
     36        md.diagnostic.spcvz=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
    3637        md.diagnostic.spcvx[pos]=0
    3738        md.diagnostic.spcvy[pos]=0
    3839        md.diagnostic.spcvz[pos]=0
    39         md.diagnostic.referential=float('NaN')*numpy.ones((md.mesh.numberofvertices,6))
     40        md.diagnostic.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
    4041
    4142        #Dirichlet Values
    42         if numpy.size(md.inversion.vx_obs)==md.mesh.numberofvertices and numpy.size(md.inversion.vy_obs)==md.mesh.numberofvertices:
    43                 print '      boundary conditions for diagnostic model: spc set as observed velocities'
     43        if isinstance(md.inversion.vx_obs,numpy.ndarray) and numpy.size(md.inversion.vx_obs,axis=0)==md.mesh.numberofvertices and isinstance(md.inversion.vy_obs,numpy.ndarray) and numpy.size(md.inversion.vy_obs,axis=0)==md.mesh.numberofvertices:
     44                #reshape to rank-2 if necessary to match spc arrays
     45                if numpy.ndim(md.inversion.vx_obs)==1:
     46                        md.inversion.vx_obs=md.inversion.vx_obs.reshape(-1,1)
     47                if numpy.ndim(md.inversion.vy_obs)==1:
     48                        md.inversion.vy_obs=md.inversion.vy_obs.reshape(-1,1)
     49                print "      boundary conditions for diagnostic model: spc set as observed velocities"
    4450                md.diagnostic.spcvx[pos]=md.inversion.vx_obs[pos]
    4551                md.diagnostic.spcvy[pos]=md.inversion.vy_obs[pos]
    4652        else:
    47                 print '      boundary conditions for diagnostic model: spc set as zero'
     53                print "      boundary conditions for diagnostic model: spc set as zero"
    4854
    4955        #segment on Ice Front
    5056        #segment on Neumann (Ice Front)
    5157#       pos=find(nodeonicefront(md.mesh.segments(:,1)) | nodeonicefront(md.mesh.segments(:,2)));
    52         pos=[i for i,(noif1,noif2) in enumerate(zip(nodeonicefront[md.mesh.segments[:,0].astype('int')-1],nodeonicefront[md.mesh.segments[:,1].astype('int')-1])) if noif1 or noif2]
     58        pos=numpy.nonzero(numpy.logical_or(nodeonicefront[md.mesh.segments[:,0].astype(int)-1],nodeonicefront[md.mesh.segments[:,1].astype(int)-1]))[0]
    5359        if   md.mesh.dimension==2:
    5460                pressureload=md.mesh.segments[pos,:]
    5561        elif md.mesh.dimension==3:
    5662#               pressureload_layer1=[md.mesh.segments(pos,1:2)  md.mesh.segments(pos,2)+md.mesh.numberofvertices2d  md.mesh.segments(pos,1)+md.mesh.numberofvertices2d  md.mesh.segments(pos,3)];
    57                 pressureload_layer1=numpy.concatenate((md.mesh.segments[pos,0:2],md.mesh.segments[pos,1]+md.mesh.numberofvertices2d,md.mesh.segments[pos,0]+md.mesh.numberofvertices2d,md.mesh.segments[pos,2]),axis=1)
     63                pressureload_layer1=numpy.hstack((md.mesh.segments[pos,0:2],md.mesh.segments[pos,1]+md.mesh.numberofvertices2d,md.mesh.segments[pos,0]+md.mesh.numberofvertices2d,md.mesh.segments[pos,2]))
    5864                pressureload=numpy.zeros((0,5))
    5965                for i in xrange(1,md.mesh.numberoflayers):
    6066#                       pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d ];
    61                         pressureload=numpy.concatenate((pressureload,numpy.concatenate((pressureload_layer1[:,0:3]+(i-1)*md.mesh.numberofvertices2d,pressureload_layer1[:,4]+(i-1)*md.mesh.numberofelements2d),axis=1)),axis=0)
     67                        pressureload=numpy.vstack((pressureload,numpy.hstack((pressureload_layer1[:,0:4]+(i-1)*md.mesh.numberofvertices2d,pressureload_layer1[:,4]+(i-1)*md.mesh.numberofelements2d))))
    6268
    6369        #Add water or air enum depending on the element
    6470#       pressureload=[pressureload 1*md.mask.elementonfloatingice(pressureload(:,end))];
    65         pressureload=numpy.concatenate((pressureload,1*md.mask.elementonfloatingice[pressureload[:,-1].astype('int')-1].reshape((-1,1))),axis=1)
     71        pressureload=numpy.hstack((pressureload,1.*md.mask.elementonfloatingice[pressureload[:,-1].astype('int')-1].reshape(-1,1)))
    6672
    6773        #plug onto model
     
    7076        #Create zeros basalforcings and surfaceforcings
    7177        if numpy.all(numpy.isnan(md.surfaceforcings.precipitation)) and (md.surfaceforcings.ispdd==1):
    72                 md.surfaceforcings.precipitation=numpy.zeros(md.mesh.numberofvertices)
    73                 print '      no surfaceforcings.precipitation specified: values set as zero'
     78                md.surfaceforcings.precipitation=numpy.zeros((md.mesh.numberofvertices,1))
     79                print "      no surfaceforcings.precipitation specified: values set as zero"
    7480        if numpy.all(numpy.isnan(md.surfaceforcings.mass_balance)) and (md.surfaceforcings.ispdd==0):
    75                 md.surfaceforcings.mass_balance=numpy.zeros(md.mesh.numberofvertices)
    76                 print '      no surfaceforcings.mass_balance specified: values set as zero'
     81                md.surfaceforcings.mass_balance=numpy.zeros((md.mesh.numberofvertices,1))
     82                print "      no surfaceforcings.mass_balance specified: values set as zero"
    7783        if numpy.all(numpy.isnan(md.basalforcings.melting_rate)):
    78                 md.basalforcings.melting_rate=numpy.zeros(md.mesh.numberofvertices)
    79                 print '      no basalforcings.melting_rate specified: values set as zero'
     84                md.basalforcings.melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
     85                print "      no basalforcings.melting_rate specified: values set as zero"
    8086        if numpy.all(numpy.isnan(md.balancethickness.thickening_rate)):
    81                 md.balancethickness.thickening_rate=numpy.zeros(md.mesh.numberofvertices)
    82                 print '      no balancethickness.thickening_rate specified: values set as zero'
     87                md.balancethickness.thickening_rate=numpy.zeros((md.mesh.numberofvertices,1))
     88                print "      no balancethickness.thickening_rate specified: values set as zero"
    8389
    84         md.prognostic.spcthickness=float('NaN')*numpy.ones(md.mesh.numberofvertices)
    85         md.balancethickness.spcthickness=float('NaN')*numpy.ones(md.mesh.numberofvertices)
     90        md.prognostic.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
     91        md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
    8692
    87         if numpy.size(md.initialization.temperature)==md.mesh.numberofvertices:
    88                 md.thermal.spctemperature=float('NaN')*numpy.ones(md.mesh.numberofvertices)
     93        if isinstance(md.initialization.temperature,numpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
     94                md.thermal.spctemperature=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
    8995#               pos=find(md.mesh.vertexonsurface); md.thermal.spctemperature(pos)=md.initialization.temperature(pos); %impose observed temperature on surface
    90                 pos=[i for i,vos in enumerate(md.mesh.vertexonsurface) if vos]
    91                 md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    # impose observed temperature on surface
    92                 if not numpy.size(md.basalforcings.geothermalflux)==md.mesh.numberofvertices:
    93                         md.basalforcings.geothermalflux=numpy.zeros(md.mesh.numberofvertices)
     96                pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
     97                md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
     98                if not isinstance(md.basalforcings.geothermalflux,numpy.ndarray) or not numpy.size(md.basalforcings.geothermalflux,axis=0)==md.mesh.numberofvertices:
     99                        md.basalforcings.geothermalflux=numpy.zeros((md.mesh.numberofvertices,1))
    94100        else:
    95                 print '      no thermal boundary conditions created: no observed temperature found'
     101                print "      no thermal boundary conditions created: no observed temperature found"
    96102
    97103        return md
  • issm/trunk/src/m/boundaryconditions/SetMarineIceSheetBC.m

    r13395 r13975  
    5353
    5454md.hydrology.spcwatercolumn=zeros(md.mesh.numberofvertices,2);
    55 pos=find(md.mesh.vertexonboundary); 
     55pos=find(md.mesh.vertexonboundary);
    5656md.hydrology.spcwatercolumn(pos,1)=1;
    5757
     
    7373%plug onto model
    7474md.diagnostic.icefront=pressureload;
    75 
    7675
    7776%Create zeros basalforcings and surfaceforcings
     
    101100        if (length(md.basalforcings.geothermalflux)~=md.mesh.numberofvertices),
    102101                md.basalforcings.geothermalflux=zeros(md.mesh.numberofvertices,1);
    103                 md.basalforcings.geothermalflux(find(md.mask.vertexongroundedice))=50*10^-3; %50mW/m2
     102                md.basalforcings.geothermalflux(find(md.mask.vertexongroundedice))=50.*10.^-3; %50mW/m2
    104103        end
    105104else
  • issm/trunk/src/m/classes/autodiff.m

    r13395 r13975  
    99                dependents   = {};
    1010                independents = {};
     11                driver       = 'fos_forward';
    1112        end
    1213        methods
     
    2425                function md = checkconsistency(obj,md,solution,analyses) % {{{
    2526
    26                 %Early return
    27                 if ~obj.isautodiff, return; end
     27                        %Early return
     28                        if ~obj.isautodiff, return; end
     29
     30                        %Driver value:
     31                        md = checkfield(md,'autodiff.driver','values',{'fos_forward','fov_forward','fov_forward_all','fos_reverse','fov_reverse','fov_reverse_all'});
     32
     33                        %go through our dependents and independents and check consistency:
     34                        for i=1:numel(obj.dependents),
     35                                dep=obj.dependents{i};
     36                                md=checkconsistency(dep,md,solution,analyses);
     37                        end
     38                        for i=1:numel(obj.independents),
     39                                indep=obj.independents{i};
     40                                md=checkconsistency(indep,md,i,solution,analyses,obj.driver);
     41                        end
    2842
    2943                end % }}}
    3044                function disp(obj) % {{{
    31                         disp(sprintf('   automatic differentiation parameters:'));
     45                        disp(sprintf('      automatic differentiation parameters:'));
    3246                        fielddisplay(obj,'isautodiff','indicates if the automatic differentiation is activated');
    33                         fielddisplay(obj,'dependents','list of dependent variables ; ex: {''Thickness'',''FrictionCoefficient''}');
    34                         fielddisplay(obj,'independents','list of independent variables ; ex: {''IceVolume'',''MassFlux''}');
     47                        fielddisplay(obj,'dependents','list of dependent variables');
     48                        fielddisplay(obj,'independents','list of independent variables');
     49                        fielddisplay(obj,'driver','ADOLC driver (''fos_forward'' or ''fov_forward'')');
    3550                end % }}}
    3651                function marshall(obj,fid) % {{{
    3752
    3853                        WriteData(fid,'object',obj,'fieldname','isautodiff','format','Boolean');
    39                        
     54                        WriteData(fid,'object',obj,'fieldname','driver','format','String');
     55
    4056                        %early return
    41                         if ~obj.isautodiff, return; end
    42 
    43                         %process dependent variables
    44                         num_dependents=numel(obj.dependents);
    45                         WriteData(fid,'data',num_dependents,'enum',AutodiffNumDependentsEnum(),'format','Integer');
    46                        
    47                         if(num_dependents),
    48                                 data=zeros(1,num_dependents);
    49                                 for i=1:num_dependents,
    50                                         data(i)=StringToEnum(obj.dependents{i});
    51                                 end
    52                                 WriteData(fid,'data',data,'enum',AutodiffDependentsEnum(),'format','DoubleMat','mattype',3);
    53                         end
    54                        
    55                         %process independent variables
    56                         num_independents=numel(obj.independents);
    57                         WriteData(fid,'data',num_independents,'enum',AutodiffNumIndependentsEnum(),'format','Integer');
    58                        
    59                         if(num_independents)
    60                                 data=zeros(1,num_independents);
    61                                 for i=1:num_independents,
    62                                         data(i)=StringToEnum(obj.independents{i});
    63                                 end
    64                                 WriteData(fid,'data',data,'enum',AutodiffIndependentsEnum(),'format','DoubleMat','mattype',3);
    65                         end
     57                        if ~obj.isautodiff,
     58                                WriteData(fid,'data',false,'enum',AutodiffMassFluxSegmentsPresentEnum(),'format','Boolean');
     59                                WriteData(fid,'data',false,'enum',AutodiffKeepEnum(),'format','Boolean');
     60                                return;
     61                        end
     62
     63                        %process dependent variables {{{
     64                        num_dependent_objects=numel(obj.dependents);
     65                        WriteData(fid,'data',num_dependent_objects,'enum',AutodiffNumDependentObjectsEnum(),'format','Integer');
     66
     67                        if(num_dependent_objects),
     68                                names=zeros(num_dependent_objects,1);
     69                                types=zeros(num_dependent_objects,1);
     70                                indices=zeros(num_dependent_objects,1);
     71
     72                                for i=1:num_dependent_objects,
     73                                        dep=obj.dependents{i};
     74
     75                                        names(i)=StringToEnum(dep.name);
     76                                        types(i)=dep.typetoscalar();
     77                                        indices(i)=dep.index;
     78                                end
     79                                WriteData(fid,'data',names,'enum',AutodiffDependentObjectNamesEnum(),'format','IntMat','mattype',3);
     80                                WriteData(fid,'data',types,'enum',AutodiffDependentObjectTypesEnum(),'format','IntMat','mattype',3);
     81                                WriteData(fid,'data',indices,'enum',AutodiffDependentObjectIndicesEnum(),'format','IntMat','mattype',3);
     82                        end
     83                        %}}}
     84                        %process independent variables {{{
     85                        num_independent_objects=numel(obj.independents);
     86                        WriteData(fid,'data',num_independent_objects,'enum',AutodiffNumIndependentObjectsEnum(),'format','Integer');
     87
     88                        if(num_independent_objects),
     89                                names=zeros(num_independent_objects,1);
     90                                types=zeros(num_independent_objects,1);
     91
     92                                for i=1:num_independent_objects,
     93                                        indep=obj.independents{i};
     94
     95                                        names(i)=StringToEnum(indep.name);
     96                                        types(i)=indep.typetoscalar();
     97                                end
     98                                WriteData(fid,'data',names,'enum',AutodiffIndependentObjectNamesEnum(),'format','IntMat','mattype',3);
     99                                WriteData(fid,'data',types,'enum',AutodiffIndependentObjectTypesEnum(),'format','IntMat','mattype',3);
     100                        end
     101                        %}}}
     102                        %if driver is fos_forward, build index:  {{{
     103                        if strcmpi(obj.driver,'fos_forward'),
     104                                index=0;
     105
     106                                for i=1:num_independent_objects,
     107                                        indep=obj.independents{i};
     108                                        if ~isnan(indep.fos_forward_index),
     109                                                index=index+indep.fos_forward_index;
     110                                                break;
     111                                        else
     112                                                if strcmpi(indep.type,'scalar'),
     113                                                        index=index+1;
     114                                                else
     115                                                        index=index+indep.nods;
     116                                                end
     117                                        end
     118                                end
     119                                index=index-1; %get c-index numbering going
     120                                WriteData(fid,'data',index,'enum',AutodiffFosForwardIndexEnum(),'format','Integer');
     121                        end
     122                        %}}}
     123                        %if driver is fos_reverse, build index:  {{{
     124                        if strcmpi(obj.driver,'fos_reverse'),
     125                                index=0;
     126
     127                                for i=1:num_dependent_objects,
     128                                        dep=obj.dependents{i};
     129                                        if ~isnan(dep.fos_reverse_index),
     130                                                index=index+dep.fos_reverse_index;
     131                                                break;
     132                                        else
     133                                                if strcmpi(dep.type,'scalar'),
     134                                                        index=index+1;
     135                                                else
     136                                                        index=index+dep.nods;
     137                                                end
     138                                        end
     139                                end
     140                                index=index-1; %get c-index numbering going
     141                                WriteData(fid,'data',index,'enum',AutodiffFosReverseIndexEnum(),'format','Integer');
     142                        end
     143                        %}}}
     144                        %if driver is fov_forward, build indices:  {{{
     145                        if strcmpi(obj.driver,'fov_forward'),
     146                                indices=0;
     147
     148                                for i=1:num_independent_objects,
     149                                        indep=obj.independents{i};
     150                                        if ~isempty(indep.fos_forward_index),
     151                                                indices=indices+indep.fov_forward_indices;
     152                                                break;
     153                                        else
     154                                                if strcmpi(indep.type,'scalar'),
     155                                                        indices=indices+1;
     156                                                else
     157                                                        indices=indices+indep.nods;
     158                                                end
     159                                        end
     160                                end
     161                                indices=indices-1; %get c-indices numbering going
     162                                WriteData(fid,'data',indices,'enum',AutodiffFovForwardIndicesEnum(),'format','IntMat','mattype',3);
     163                        end
     164                        %}}}
     165                        %deal with mass fluxes:  {{{
     166                        mass_flux_segments=cell(0,1);
     167                        for i=1:num_dependent_objects,
     168                                dep=obj.dependents{i};
     169                                if strcmpi(dep.name,'MassFlux'),
     170                                        mass_flux_segments{end+1,1}=dep.segments;
     171                                end
     172                        end
     173                        if ~isempty(mass_flux_segments),
     174                                WriteData(fid,'data',mass_flux_segments,'enum',MassFluxSegmentsEnum(),'format','MatArray');
     175                                flag=true;
     176                        else
     177                                flag=false;
     178                        end
     179                        WriteData(fid,'data',flag,'enum',AutodiffMassFluxSegmentsPresentEnum(),'format','Boolean');
     180                        %}}}
     181                        %deal with trace keep on: {{{
     182                        keep=false;
     183
     184                        %From ADOLC userdoc:
     185                        % The optional integer argument keep of trace on determines whether the numerical values of all active variables are
     186                        % recorded in a buffered temporary array or file called the taylor stack. This option takes effect if keep = 1 and
     187                        % prepares the scene for an immediately following gradient evaluation by a call to a routine implementing the reverse
     188                        % mode as described in the Section 4 and Section 5.
     189                        %
     190
     191                        if length(obj.driver)<=3,
     192                                keep=false; %there is no "_reverse" string within the driver string:
     193                        else
     194                                if strncmpi(obj.driver(4:end),'_reverse',8),
     195                                        keep=true;
     196                                else
     197                                        keep=false;
     198                                end
     199                        end
     200                        WriteData(fid,'data',keep,'enum',AutodiffKeepEnum(),'format','Boolean');
     201                        %}}}
    66202
    67203                end % }}}
  • issm/trunk/src/m/classes/autodiff.py

    r13395 r13975  
    11#module imports
     2import numpy
     3from dependent import *
     4from independent import *
    25from fielddisplay import fielddisplay
    36from EnumDefinitions import *
     
    1417
    1518        #properties
    16         def __init__(self):
    17                 # {{{ Properties
    18                 self.isautodiff = False
     19        def __init__(self,*args):    # {{{
     20                self.isautodiff   = False
     21                self.dependents   = []
     22                self.independents = []
     23                self.driver       = 'fos_forward'
    1924
    20                 #set defaults
    21                 self.setdefaultparameters()
     25                if not len(args):
     26                        self.setdefaultparameters()
     27                else:
     28                        raise RuntimeError("constructor not supported")
     29        # }}}
    2230
    23                 #}}}
    24         def __repr__(self):
    25                 # {{{ Display
    26                 string='   automatic differentiation parameters:'
    27                 string="%s\n%s"%(string,fielddisplay(self,'isautodiff','indicates if the automatic differentiation is activated'))
    28                 return string
    29                 #}}}
    30         def setdefaultparameters(self):
    31                 # {{{setdefaultparameters
     31        def __repr__(self):    # {{{
     32                s ="      automatic differentiation parameters:\n"
     33
     34                s+="%s\n" % fielddisplay(self,'isautodiff',"indicates if the automatic differentiation is activated")
     35                s+="%s\n" % fielddisplay(self,'dependents',"list of dependent variables")
     36                s+="%s\n" % fielddisplay(self,'independents',"list of independent variables")
     37                s+="%s\n" % fielddisplay(self,'driver',"ADOLC driver ('fos_forward' or 'fov_forward')")
     38
     39                return s
     40        # }}}
     41
     42        def setdefaultparameters(self):    # {{{
    3243                return self
    33         #}}}
     44        # }}}
    3445
    3546        def checkconsistency(self,md,solution,analyses):    # {{{
     47
     48                #Early return
     49                if not self.isautodiff:
     50                        return md
     51
     52                #Driver value:
     53                md = checkfield(md,'autodiff.driver','values',['fos_forward','fov_forward','fov_forward_all','fos_reverse','fov_reverse','fov_reverse_all'])
     54
     55                #go through our dependents and independents and check consistency:
     56                for dep in self.dependents:
     57                        dep.checkconsistency(md,solution,analyses)
     58                for i,indep in enumerate(self.independents):
     59                        indep.checkconsistency(md,i,solution,analyses,self.driver)
     60
    3661                return md
    3762        # }}}
     
    3964        def marshall(self,fid):    # {{{
    4065                WriteData(fid,'object',self,'fieldname','isautodiff','format','Boolean')
     66                WriteData(fid,'object',self,'fieldname','driver','format','String')
     67
     68                #early return
     69                if not self.isautodiff:
     70                        WriteData(fid,'data',False,'enum',AutodiffMassFluxSegmentsPresentEnum(),'format','Boolean')
     71                        WriteData(fid,'data',False,'enum',AutodiffKeepEnum(),'format','Boolean')
     72                        return
     73
     74                #process dependent variables {{{
     75                num_dependent_objects=len(self.dependents)
     76                WriteData(fid,'data',num_dependent_objects,'enum',AutodiffNumDependentObjectsEnum(),'format','Integer')
     77
     78                if num_dependent_objects:
     79                        names=numpy.zeros(num_dependent_objects)
     80                        types=numpy.zeros(num_dependent_objects)
     81                        indices=numpy.zeros(num_dependent_objects)
     82
     83                        for i,dep in enumerate(self.dependents):
     84                                names[i]=StringToEnum(dep.name)[0]
     85                                types[i]=dep.typetoscalar()
     86                                indices[i]=dep.index
     87
     88                        WriteData(fid,'data',names,'enum',AutodiffDependentObjectNamesEnum(),'format','IntMat','mattype',3)
     89                        WriteData(fid,'data',types,'enum',AutodiffDependentObjectTypesEnum(),'format','IntMat','mattype',3)
     90                        WriteData(fid,'data',indices,'enum',AutodiffDependentObjectIndicesEnum(),'format','IntMat','mattype',3)
     91                #}}}
     92
     93                #process independent variables {{{
     94                num_independent_objects=len(self.independents)
     95                WriteData(fid,'data',num_independent_objects,'enum',AutodiffNumIndependentObjectsEnum(),'format','Integer')
     96
     97                if num_independent_objects:
     98                        names=numpy.zeros(num_independent_objects)
     99                        types=numpy.zeros(num_independent_objects)
     100
     101                        for i,indep in enumerate(self.independents):
     102                                names[i]=StringToEnum(indep.name)[0]
     103                                types[i]=indep.typetoscalar()
     104
     105                        WriteData(fid,'data',names,'enum',AutodiffIndependentObjectNamesEnum(),'format','IntMat','mattype',3)
     106                        WriteData(fid,'data',types,'enum',AutodiffIndependentObjectTypesEnum(),'format','IntMat','mattype',3)
     107                #}}}
     108
     109                #if driver is fos_forward, build index:  {{{
     110                if strcmpi(self.driver,'fos_forward'):
     111                        index=0
     112
     113                        for indep in self.independents:
     114                                if not numpy.isnan(indep.fos_forward_index):
     115                                        index+=indep.fos_forward_index
     116                                        break
     117                                else:
     118                                        if strcmpi(indep.type,'scalar'):
     119                                                index+=1
     120                                        else:
     121                                                index+=indep.nods
     122
     123                        index-=1    #get c-index numbering going
     124                        WriteData(fid,'data',index,'enum',AutodiffFosForwardIndexEnum(),'format','Integer')
     125                #}}}
     126
     127                #if driver is fos_reverse, build index:  {{{
     128                if strcmpi(self.driver,'fos_reverse'):
     129                        index=0
     130
     131                        for dep in self.dependents:
     132                                if not numpy.isnan(dep.fos_reverse_index):
     133                                        index+=dep.fos_reverse_index
     134                                        break
     135                                else:
     136                                        if strcmpi(dep.type,'scalar'):
     137                                                index+=1
     138                                        else:
     139                                                index+=dep.nods
     140
     141                        index-=1    #get c-index numbering going
     142                        WriteData(fid,'data',index,'enum',AutodiffFosReverseIndexEnum(),'format','Integer')
     143                #}}}
     144
     145                #if driver is fov_forward, build indices:  {{{
     146                if strcmpi(self.driver,'fov_forward'):
     147                        indices=0
     148
     149                        for indep in self.independents:
     150                                if indep.fos_forward_index:
     151                                        indices+=indep.fov_forward_indices
     152                                        break
     153                                else:
     154                                        if strcmpi(indep.type,'scalar'):
     155                                                indices+=1
     156                                        else:
     157                                                indices+=indep.nods
     158
     159                        indices-=1    #get c-indices numbering going
     160                        WriteData(fid,'data',indices,'enum',AutodiffFovForwardIndicesEnum(),'format','IntMat','mattype',3)
     161                #}}}
     162
     163                #deal with mass fluxes:  {{{
     164                mass_flux_segments=[dep.segments for dep in self.dependents if strcmpi(dep.name,'MassFlux')]
     165
     166                if mass_flux_segments:
     167                        WriteData(fid,'data',mass_flux_segments,'enum',MassFluxSegmentsEnum(),'format','MatArray')
     168                        flag=True
     169                else:
     170                        flag=False
     171                WriteData(fid,'data',flag,'enum',AutodiffMassFluxSegmentsPresentEnum(),'format','Boolean')
     172                #}}}
     173
     174                #deal with trace keep on: {{{
     175                keep=False
     176
     177                #From ADOLC userdoc:
     178                # The optional integer argument keep of trace on determines whether the numerical values of all active variables are
     179                # recorded in a buffered temporary array or file called the taylor stack. This option takes effect if keep = 1 and
     180                # prepares the scene for an immediately following gradient evaluation by a call to a routine implementing the reverse
     181                # mode as described in the Section 4 and Section 5.
     182                #
     183
     184                if len(self.driver)<=3:
     185                        keep=False    #there is no "_reverse" string within the driver string:
     186                else:
     187                        if strncmpi(self.driver[3:],'_reverse',8):
     188                                keep=True
     189                        else:
     190                                keep=False
     191                WriteData(fid,'data',keep,'enum',AutodiffKeepEnum(),'format','Boolean')
     192                #}}}
     193
     194                return
    41195        # }}}
    42196
  • issm/trunk/src/m/classes/bamggeom.py

    r13395 r13975  
     1import numpy
     2
    13class bamggeom(object):
    24        """
     
    810
    911        def __init__(self,*args):    # {{{
    10                 self.Vertices=[]
    11                 self.Edges=[]
    12                 self.TangentAtEdges=[]
    13                 self.Corners=[]
    14                 self.RequiredVertices=[]
    15                 self.RequiredEdges=[]
    16                 self.CrackedEdges=[]
    17                 self.SubDomains=[]
     12                self.Vertices=numpy.empty((0,3))
     13                self.Edges=numpy.empty((0,3))
     14                self.TangentAtEdges=numpy.empty((0,4))
     15                self.Corners=numpy.empty((0,1))
     16                self.RequiredVertices=numpy.empty((0,1))
     17                self.RequiredEdges=numpy.empty((0,1))
     18                self.CrackedEdges=numpy.empty((0,0))
     19                self.SubDomains=numpy.empty((0,4))
    1820
    1921                if not len(args):
  • issm/trunk/src/m/classes/bamgmesh.py

    r13395 r13975  
     1import numpy
     2
    13class bamgmesh(object):
    24        """
     
    810
    911        def __init__(self,*args):    # {{{
    10                 self.Vertices=[]
    11                 self.Edges=[]
    12                 self.Triangles=[]
    13                 self.Quadrilaterals=[]
    14                 self.IssmEdges=[]
    15                 self.IssmSegments=[]
    16                 self.VerticesOnGeomVertex=[]
    17                 self.VerticesOnGeomEdge=[]
    18                 self.EdgesOnGeomEdge=[]
    19                 self.SubDomains=[]
    20                 self.SubDomainsFromGeom=[]
    21                 self.ElementConnectivity=[]
    22                 self.NodalConnectivity=[]
    23                 self.NodalElementConnectivity=[]
    24                 self.CrackedVertices=[]
    25                 self.CrackedEdges=[]
     12                self.Vertices=numpy.empty((0,3))
     13                self.Edges=numpy.empty((0,3))
     14                self.Triangles=numpy.empty((0,0))
     15                self.Quadrilaterals=numpy.empty((0,0))
     16                self.IssmEdges=numpy.empty((0,0))
     17                self.IssmSegments=numpy.empty((0,0))
     18                self.VerticesOnGeomVertex=numpy.empty((0,0))
     19                self.VerticesOnGeomEdge=numpy.empty((0,0))
     20                self.EdgesOnGeomEdge=numpy.empty((0,0))
     21                self.SubDomains=numpy.empty((0,4))
     22                self.SubDomainsFromGeom=numpy.empty((0,0))
     23                self.ElementConnectivity=numpy.empty((0,0))
     24                self.NodalConnectivity=numpy.empty((0,0))
     25                self.NodalElementConnectivity=numpy.empty((0,0))
     26                self.CrackedVertices=numpy.empty((0,0))
     27                self.CrackedEdges=numpy.empty((0,0))
    2628
    2729                if not len(args):
  • issm/trunk/src/m/classes/clusters/discover.m

    r13395 r13975  
    106106                         fprintf(fid,'#PBS -e %s.errlog \n\n',modelname);
    107107                         fprintf(fid,'. /usr/share/modules/init/bash\n\n');
    108                          fprintf(fid,'module load comp/intel-10.1.023\n');
     108                         fprintf(fid,'module purge\n');
     109                         fprintf(fid,'module load comp/intel-11.1.038\n');
    109110                         fprintf(fid,'module load mpi/impi-4.0.3.008\n');
    110111                         fprintf(fid,'module load lib/mkl-10.1.2.024\n\n');
  • issm/trunk/src/m/classes/clusters/generic.m

    r13395 r13975  
    1414                interactive=1;
    1515                codepath=[issmdir() '/bin'];
     16                etcpath=[issmdir() '/etc'];
    1617                executionpath=[issmdir() '/execution'];
    1718                valgrind=[issmdir() '/externalpackages/valgrind/install/bin/valgrind'];
     
    4546                        disp(sprintf('    codepath: %s',cluster.codepath));
    4647                        disp(sprintf('    executionpath: %s',cluster.executionpath));
     48                        disp(sprintf('    etcpath: %s',cluster.executionpath));
    4749                        disp(sprintf('    valgrind: %s',cluster.valgrind));
    4850                        disp(sprintf('    valgrindlib: %s',cluster.valgrindlib));
     
    190192
    191193                        disp('launching solution sequence on remote cluster');
    192                         launchcommand=['source ' issmdir '/etc/environment.sh && cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
     194                        launchcommand=['source ' cluster.etcpath '/environment.sh && cd ' cluster.executionpath ' && rm -rf ./' dirname ' && mkdir ' dirname ...
    193195                                ' && cd ' dirname ' && mv ../' dirname '.tar.gz ./ && tar -zxf ' dirname '.tar.gz  && source  ' modelname '.queue '];
    194196                        issmssh(cluster.name,cluster.login,cluster.port,launchcommand);
  • issm/trunk/src/m/classes/diagnostic.m

    r13395 r13975  
    3838                         %maximum of non-linear iterations.
    3939                         obj.maxiter=100;
    40                          
     40
    4141                         %Convergence criterion: absolute, relative and residual
    4242                         obj.restol=10^-4;
    4343                         obj.reltol=0.01;
    4444                         obj.abstol=10;
    45                          
     45
    4646                         obj.stokesreconditioning=10^13;
    4747                         obj.shelf_dampening=0;
     
    9292
    9393                        %singular solution
    94                         if ~any((~isnan(md.diagnostic.spcvx)+~isnan(md.diagnostic.spcvy))==2),
     94                        if ~(any(~isnan(md.diagnostic.spcvx)) & any(~isnan(md.diagnostic.spcvy))),
    9595                                md = checkmessage(md,['model is not well posed (singular). You need at least one node with fixed velocity!']);
    9696                        end
  • issm/trunk/src/m/classes/diagnostic.py

    r13395 r13975  
    22import numpy
    33import sys
     4import copy
    45from fielddisplay import fielddisplay
    56from EnumDefinitions import *
     
    186187
    187188                #marshall ice front
    188                 data=self.icefront
     189                data=copy.deepcopy(self.icefront)
    189190                data[numpy.nonzero(data[:,-1]==0),-1]=AirEnum()
    190191                data[numpy.nonzero(data[:,-1]==1),-1]=WaterEnum()
  • issm/trunk/src/m/classes/flaim.m

    r13395 r13975  
    5959                        fielddisplay(obj,'usevalueordering'   ,'flag to consider target values for flight path evaluation');
    6060                        fielddisplay(obj,'split_antimeridian' ,'flag to split polygons on the antimeridian');
    61                        
     61
    6262                        disp(sprintf('\n      Optimization:'));
    6363                        fielddisplay(obj,'path_optimize'     ,'optimize? (default false)');
  • issm/trunk/src/m/classes/flowequation.py

    r13395 r13975  
    11#module imports
    22import numpy
     3import copy
    34from fielddisplay import fielddisplay
    45from EnumDefinitions import *
     
    6768                                md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements],'values',[1,2])
    6869                        else:
    69                                 md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',range(0,7+1))
    70                                 md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements],'values',range(0,7+1))
     70                                md = checkfield(md,'flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',numpy.arange(0,7+1))
     71                                md = checkfield(md,'flowequation.element_equation','size',[md.mesh.numberofelements],'values',numpy.arange(0,7+1))
    7172                        if not (self.ismacayealpattyn or self.ishutter or self.isstokes or self.isl1l2):
    7273                                md.checkmessage("no element types set for this model. At least one of ismacayealpattyn, ishutter or isstokes need to be =1")
     
    8990                WriteData(fid,'object',self,'fieldname','borderstokes','format','DoubleMat','mattype',1)
    9091                #convert approximations to enums
    91                 data=self.vertex_equation
     92                data=copy.deepcopy(self.vertex_equation)
    9293                data[numpy.nonzero(data==0)]=NoneApproximationEnum()
    9394                data[numpy.nonzero(data==1)]=HutterApproximationEnum()
     
    100101                data[numpy.nonzero(data==8)]=L1L2ApproximationEnum()
    101102                WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum(),'format','DoubleMat','mattype',1)
    102                 data=self.element_equation
     103                data=copy.deepcopy(self.element_equation)
    103104                data[numpy.nonzero(data==0)]=NoneApproximationEnum()
    104105                data[numpy.nonzero(data==1)]=HutterApproximationEnum()
  • issm/trunk/src/m/classes/groundingline.m

    r13395 r13975  
    2525                        %basal melting rate correction:
    2626                        obj.melting_rate=0;
    27 
    2827
    2928                end % }}}
  • issm/trunk/src/m/classes/initialization.py

    r13395 r13975  
    2424                self.pressure      = float('NaN')
    2525                self.temperature   = float('NaN')
     26                self.surfacetemp   = float('NaN')
     27                self.basaltemp     = float('NaN')
    2628                self.watercolumn   = float('NaN')
    2729                self.waterfraction = float('NaN')
     
    4143                string="%s\n%s"%(string,fielddisplay(self,'pressure','pressure field'))
    4244                string="%s\n%s"%(string,fielddisplay(self,'temperature','temperature in Kelvins'))
     45                string="%s\n%s"%(string,fielddisplay(self,'surfacetemp','surface temperature in Kelvins'))
     46                string="%s\n%s"%(string,fielddisplay(self,'basaltemp','basal temperature in Kelvins'))
    4347                string="%s\n%s"%(string,fielddisplay(self,'watercolumn','thickness of subglacial water'))
    4448                string="%s\n%s"%(string,fielddisplay(self,'waterfraction','fraction of water in the ice'))
     
    8690                WriteData(fid,'data',self.pressure,'format','DoubleMat','mattype',1,'enum',PressureEnum())
    8791                WriteData(fid,'data',self.temperature,'format','DoubleMat','mattype',1,'enum',TemperatureEnum())
     92                WriteData(fid,'data',self.surfacetemp,'format','DoubleMat','mattype',1,'enum',TemperatureSurfaceEnum())
     93                WriteData(fid,'data',self.basaltemp,'format','DoubleMat','mattype',1,'enum',TemperatureBasalEnum())
    8894                WriteData(fid,'data',self.watercolumn,'format','DoubleMat','mattype',1,'enum',WatercolumnEnum())
    8995                WriteData(fid,'data',self.waterfraction,'format','DoubleMat','mattype',1,'enum',WaterfractionEnum())
  • issm/trunk/src/m/classes/inversion.py

    r13395 r13975  
    11#module imports
    22import numpy
     3import copy
    34from fielddisplay import fielddisplay
    45from EnumDefinitions import *
     
    9697                #inversed parameter (10^8 for B, 50 for drag) and can be decreased
    9798                #after the first iterations
    98                 self.gradient_scaling=50*numpy.ones(self.nsteps)
     99                self.gradient_scaling=50*numpy.ones((self.nsteps,1))
    99100
    100101                #several responses can be used:
    101                 self.cost_functions=101*numpy.ones(self.nsteps)
     102                self.cost_functions=101*numpy.ones((self.nsteps,1))
    102103
    103104                #step_threshold is used to speed up control method. When
     
    124125
    125126                num_controls=numpy.size(md.inversion.control_parameters)
    126                 num_costfunc=numpy.size(md.inversion.cost_functions,1)
     127                num_costfunc=numpy.size(md.inversion.cost_functions,axis=1)
    127128
    128129                md = checkfield(md,'inversion.iscontrol','values',[0,1])
    129130                md = checkfield(md,'inversion.tao','values',[0,1])
    130131                md = checkfield(md,'inversion.incomplete_adjoint','values',[0,1])
    131                 md = checkfield(md,'inversion.control_parameters','cell',1,'values',['BalancethicknessThickeningRate','FrictionCoefficient','MaterialsRheologyBbar','Vx','Vy'])
     132                md = checkfield(md,'inversion.control_parameters','cell',1,'values',['BalancethicknessThickeningRate','FrictionCoefficient','MaterialsRheologyBbar','MaterialsRheologyZbar','Vx','Vy'])
    132133                md = checkfield(md,'inversion.nsteps','numel',[1],'>=',1)
    133134                md = checkfield(md,'inversion.maxiter_per_step','size',[md.inversion.nsteps],'>=',0)
     
    171172
    172173                #process control parameters
    173                 num_control_parameters=numpy.size(self.control_parameters)
    174                 data=[StringToEnum(self.control_parameters[i])[0] for i in xrange(0,num_control_parameters)]
     174                num_control_parameters=len(self.control_parameters)
     175                data=numpy.array([StringToEnum(control_parameter)[0] for control_parameter in self.control_parameters]).reshape(1,-1)
    175176                WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3)
    176177                WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer')
    177178
    178179                #process cost functions
    179                 num_cost_functions=size(self.cost_functions,1)
    180                 data=self.cost_functions
     180                num_cost_functions=numpy.size(self.cost_functions,axis=1)
     181                data=copy.deepcopy(self.cost_functions)
    181182                data[numpy.nonzero(data==101)]=SurfaceAbsVelMisfitEnum()
    182183                data[numpy.nonzero(data==102)]=SurfaceRelVelMisfitEnum()
  • issm/trunk/src/m/classes/matice.py

    r13395 r13975  
    88class matice(object):
    99        """
    10         MATERIALS class definition
     10        MATICE class definition
    1111
    1212           Usage:
  • issm/trunk/src/m/classes/mesh.m

    r13395 r13975  
    1515                numberofvertices            = 0;
    1616                numberofedges               = 0;
    17                
     17
    1818                lat                         = NaN
    1919                long                        = NaN
     
    158158                        fielddisplay(obj,'lowerelements','lower element list (NaN for element on the lower layer');
    159159                        fielddisplay(obj,'vertexonboundary','vertices on the boundary of the domain flag list');
    160                        
     160
    161161                        fielddisplay(obj,'segments','edges on domain boundary (vertex1 vertex2 element)');
    162162                        fielddisplay(obj,'segmentmarkers','number associated to each segment');
  • issm/trunk/src/m/classes/mesh.py

    r13395 r13975  
    132132                md = checkfield(md,'mesh.y','NaN',1,'size',[md.mesh.numberofvertices])
    133133                md = checkfield(md,'mesh.z','NaN',1,'size',[md.mesh.numberofvertices])
    134                 md = checkfield(md,'mesh.elements','NaN',1,'>',0,'values',range(1,md.mesh.numberofvertices+1))
     134                md = checkfield(md,'mesh.elements','NaN',1,'>',0,'values',numpy.arange(1,md.mesh.numberofvertices+1))
    135135                if md.mesh.dimension==2:
    136136                        md = checkfield(md,'mesh.elements','size',[md.mesh.numberofelements,3])
    137137                else:
    138138                        md = checkfield(md,'mesh.elements','size',[md.mesh.numberofelements,6])
    139                 if numpy.any(numpy.logical_not(ismember(range(1,md.mesh.numberofvertices+1),md.mesh.elements))):
     139                if numpy.any(numpy.logical_not(ismember(numpy.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))):
    140140                        md.checkmessage("orphan nodes have been found. Check the mesh outline")
    141141                md = checkfield(md,'mesh.dimension','values',[2,3])
  • issm/trunk/src/m/classes/model/model.m

    r13395 r13975  
    55
    66classdef model
    7     properties (SetAccess=public) %Model fields
    8                  % {{{
    9                  %Careful here: no other class should be used as default value this is a bug of matlab
    10                  mesh             = 0;
    11                  mask             = 0;
    12 
    13                  geometry         = 0;
    14                  constants        = 0;
    15                  surfaceforcings  = 0;
    16                  basalforcings    = 0;
    17                  materials        = 0;
    18                  friction         = 0;
    19                  flowequation     = 0;
    20                  timestepping     = 0;
    21                  initialization   = 0;
    22                  rifts            = 0;
    23 
    24                  debug            = 0;
    25                  verbose          = 0;
    26                  settings         = 0;
    27                  solver           = 0;
    28                  cluster          = 0;
    29 
    30                  balancethickness = 0;
    31                  diagnostic       = 0;
    32                  groundingline    = 0;
    33                  hydrology        = 0;
    34                  prognostic       = 0;
    35                  thermal          = 0;
    36                  steadystate      = 0;
    37                  transient        = 0;
    38 
    39                  autodiff         = 0;
    40                  flaim            = 0;
    41                  inversion        = 0;
    42                  qmu              = 0;
    43 
    44                  results          = 0;
    45                  radaroverlay     = 0;
    46                  miscellaneous    = 0;
    47                  private          = 0;
    48 
    49                  %}}}
    50          end
    51          methods (Static)
    52                  function md = loadobj(md) % {{{
    53                          % This function is directly called by matlab when a model object is
    54                          % loaded. If the input is a struct it is an old version of model and
    55                          % old fields must be recovered (make sure they are in the deprecated
    56                          % model properties)
    57 
    58                          if verLessThan('matlab','7.9'),
    59                                  disp('Warning: your matlab version is old and there is a risk that load does not work correctly');
    60                                  disp('         if the model is not loaded correctly, rename temporarily loadobj so that matlab does not use it');
    61 
    62                                  % This is a Matlab bug: all the fields of md have their default value
    63                                  % Example of error message:
    64                                  % Warning: Error loading an object of class 'model':
    65                                  % Undefined function or method 'exist' for input arguments of type 'cell'
    66                                  %
    67                                  % This has been fixed in MATLAB 7.9 (R2009b) and later versions
    68                          end
    69 
    70                          if isstruct(md)
    71                                  disp('Recovering model object from a previous version');
    72                                  md = structtomodel(model,md);
    73                          end
    74 
    75                          %2012 August 4th
    76                          if isa(md.materials,'materials'),
    77                                  disp('Recovering old materials');
    78                                  if numel(md.materials.rheology_Z)==1 & isnan(md.materials.rheology_Z),
    79                                          md.materials=matice(md.materials);
    80                                  else
    81                                          md.materials=matdamageice(md.materials);
    82                                  end
    83                          end
    84 
    85                  end% }}}
    86          end
    87          methods
    88                  function md = model(varargin) % {{{
    89 
    90                          switch nargin
    91                                  case 0
    92                                          md=setdefaultparameters(md);
    93                                  otherwise
    94                                          error('model constructor error message: 0 of 1 argument only in input.');
    95                                  end
    96                  end
    97                  %}}}
    98                  function md = checkmessage(md,string) % {{{
    99                          if(nargout~=1) error('wrong usage, model must be an output'); end
    100                          disp(['model not consistent: ' string]);
    101                          md.private.isconsistent=false;
    102                  end
    103                  %}}}
    104                  function md = collapse(md)% {{{
    105                          %COLLAPSE - collapses a 3d mesh into a 2d mesh
    106                          %
    107                          %   This routine collapses a 3d model into a 2d model
    108                          %   and collapses all the fileds of the 3d model by
    109                          %   taking their depth-averaged values
    110                          %
    111                          %   Usage:
    112                          %      md=collapse(md)
    113                          %
    114                          %   See also: EXTRUDE, MODELEXTRACT
    115 
    116                          %Check that the model is really a 3d model
    117                          if ~md.mesh.dimension==3,
    118                                  error('collapse error message: only 3d mesh can be collapsed')
    119                          end
    120 
    121                          %Start with changing alle the fields from the 3d mesh
    122 
    123                          %drag is limited to nodes that are on the bedrock.
    124                          md.friction.coefficient=project2d(md,md.friction.coefficient,1);
    125 
    126                          %p and q (same deal, except for element that are on the bedrock: )
    127                          md.friction.p=project2d(md,md.friction.p,1);
    128                          md.friction.q=project2d(md,md.friction.q,1);
    129 
    130                          %observations
    131                          if ~isnan(md.inversion.vx_obs), md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers); end;
    132                          if ~isnan(md.inversion.vy_obs), md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers); end;
    133                          if ~isnan(md.inversion.vel_obs), md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers); end;
    134                          if ~isnan(md.inversion.cost_functions_coefficients), md.inversion.cost_functions_coefficients=project2d(md,md.inversion.cost_functions_coefficients,md.mesh.numberoflayers); end;
    135                          if numel(md.inversion.min_parameters)>1, md.inversion.min_parameters=project2d(md,md.inversion.min_parameters,md.mesh.numberoflayers); end;
    136                          if numel(md.inversion.max_parameters)>1, md.inversion.max_parameters=project2d(md,md.inversion.max_parameters,md.mesh.numberoflayers); end;
    137                          if ~isnan(md.surfaceforcings.mass_balance),
    138                                  md.surfaceforcings.mass_balance=project2d(md,md.surfaceforcings.mass_balance,md.mesh.numberoflayers);
    139                          end;
    140                          if ~isnan(md.balancethickness.thickening_rate), md.balancethickness.thickening_rate=project2d(md,md.balancethickness.thickening_rate,md.mesh.numberoflayers); end;
    141 
    142                          %results
    143                          if ~isnan(md.initialization.vx),md.initialization.vx=DepthAverage(md,md.initialization.vx);end;
    144                          if ~isnan(md.initialization.vy),md.initialization.vy=DepthAverage(md,md.initialization.vy);end;
    145                          if ~isnan(md.initialization.vz),md.initialization.vz=DepthAverage(md,md.initialization.vz);end;
    146                          if ~isnan(md.initialization.vel),md.initialization.vel=DepthAverage(md,md.initialization.vel);end;
    147                          if ~isnan(md.initialization.temperature),md.initialization.temperature=DepthAverage(md,md.initialization.temperature);end;
    148 
    149                          %bedinfo and surface info
    150                          md.mesh.elementonbed=ones(md.mesh.numberofelements2d,1);
    151                          md.mesh.elementonsurface=ones(md.mesh.numberofelements2d,1);
    152                          md.mesh.vertexonbed=ones(md.mesh.numberofvertices2d,1);
    153                          md.mesh.vertexonsurface=ones(md.mesh.numberofvertices2d,1);
    154 
    155                          %elementstype
    156                          if ~isnan(md.flowequation.element_equation)
    157                                  md.flowequation.element_equation=project2d(md,md.flowequation.element_equation,1);
    158                                  md.flowequation.vertex_equation=project2d(md,md.flowequation.vertex_equation,1);
    159                                  md.flowequation.bordermacayeal=project2d(md,md.flowequation.bordermacayeal,1);
    160                                  md.flowequation.borderpattyn=project2d(md,md.flowequation.borderpattyn,1);
    161                                  md.flowequation.borderstokes=project2d(md,md.flowequation.borderstokes,1);
    162                          end   
    163 
    164                          %boundary conditions
    165                          md.diagnostic.spcvx=project2d(md,md.diagnostic.spcvx,md.mesh.numberoflayers);
    166                          md.diagnostic.spcvy=project2d(md,md.diagnostic.spcvy,md.mesh.numberoflayers);
    167                          md.diagnostic.spcvz=project2d(md,md.diagnostic.spcvz,md.mesh.numberoflayers);
    168                          md.diagnostic.referential=project2d(md,md.diagnostic.referential,md.mesh.numberoflayers);
    169                          md.prognostic.spcthickness=project2d(md,md.prognostic.spcthickness,md.mesh.numberoflayers);
    170                          md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers);
    171 
    172                          %Extrusion of Neumann BC
    173                          if ~isnan(md.diagnostic.icefront),
    174                                  numberofneumann2d=size(md.diagnostic.icefront,1)/(md.mesh.numberoflayers-1);
    175                                  md.diagnostic.icefront=[md.diagnostic.icefront(1:numberofneumann2d,1:2) md.diagnostic.icefront(1:numberofneumann2d,5:6)]; %Add two columns on the first layer
    176                          end
    177 
    178                          %materials
    179                          md.materials.rheology_B=DepthAverage(md,md.materials.rheology_B);
    180                          md.materials.rheology_n=project2d(md,md.materials.rheology_n,1);
    181                          if isa(md.materials,'matdamageice')
    182                                  md.materials.rheology_Z=DepthAverage(md,md.materials.rheology_Z);
    183                          end
    184 
    185                          %special for thermal modeling:
    186                          md.basalforcings.melting_rate=project2d(md,md.basalforcings.melting_rate,1);
    187                          md.basalforcings.geothermalflux=project2d(md,md.basalforcings.geothermalflux,1); %bedrock only gets geothermal flux
    188 
    189                          %update of connectivity matrix
    190                          md.mesh.average_vertex_connectivity=25;
    191 
    192                          %Collapse the mesh
    193                          nodes2d=md.mesh.numberofvertices2d;
    194                          elements2d=md.mesh.numberofelements2d;
    195 
    196                          %parameters
    197                          md.geometry.surface=project2d(md,md.geometry.surface,1);
    198                          md.geometry.thickness=project2d(md,md.geometry.thickness,1);
    199                          md.geometry.bed=project2d(md,md.geometry.bed,1);
    200                          md.geometry.bathymetry=project2d(md,md.geometry.bathymetry,1);
    201                          md.mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1);
    202                          md.mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1);
    203                          md.mask.elementonfloatingice=project2d(md,md.mask.elementonfloatingice,1);
    204                          md.mask.vertexonfloatingice=project2d(md,md.mask.vertexonfloatingice,1);
    205                          md.mask.elementongroundedice=project2d(md,md.mask.elementongroundedice,1);
    206                          md.mask.vertexongroundedice=project2d(md,md.mask.vertexongroundedice,1);
    207                          md.mask.elementonwater=project2d(md,md.mask.elementonwater,1);
    208                          md.mask.vertexonwater=project2d(md,md.mask.vertexonwater,1);
    209 
    210                          %lat long
    211                          if numel(md.mesh.lat) ==md.mesh.numberofvertices,  md.mesh.lat=project2d(md,md.mesh.lat,1); end
    212                          if numel(md.mesh.long)==md.mesh.numberofvertices, md.mesh.long=project2d(md,md.mesh.long,1); end
    213 
    214                          %Initialize with the 2d mesh
    215                          md.mesh.x=md.mesh.x2d;
    216                          md.mesh.y=md.mesh.y2d;
    217                          md.mesh.z=zeros(size(md.mesh.x2d));
    218                          md.mesh.numberofvertices=md.mesh.numberofvertices2d;
    219                          md.mesh.numberofelements=md.mesh.numberofelements2d;
    220                          md.mesh.elements=md.mesh.elements2d;
    221 
    222                          %Keep a trace of lower and upper nodes
    223                          md.mesh.lowervertex=NaN;
    224                          md.mesh.uppervertex=NaN;
    225                          md.mesh.lowerelements=NaN;
    226                          md.mesh.upperelements=NaN;
    227 
    228                          %Remove old mesh
    229                          md.mesh.x2d=NaN;
    230                          md.mesh.y2d=NaN;
    231                          md.mesh.elements2d=NaN;
    232                          md.mesh.numberofelements2d=md.mesh.numberofelements;
    233                          md.mesh.numberofvertices2d=md.mesh.numberofvertices;
    234                          md.mesh.numberoflayers=0;
    235 
    236                          %Update mesh type
    237                          md.mesh.dimension=2;
    238                  end % }}}
    239                  function md2 = extract(md,area) % {{{
    240                          %extract - extract a model according to an Argus contour or flag list
    241                          %
    242                          %   This routine extracts a submodel from a bigger model with respect to a given contour
    243                          %   md must be followed by the corresponding exp file or flags list
    244                          %   It can either be a domain file (argus type, .exp extension), or an array of element flags.
    245                          %   If user wants every element outside the domain to be
    246                          %   extract2d, add '~' to the name of the domain file (ex: '~Pattyn.exp');
    247                          %   an empty string '' will be considered as an empty domain
    248                          %   a string 'all' will be considered as the entire domain
    249                          %   add an argument 0 if you do not want the elements to be checked (faster)
    250                          %
    251                          %   Usage:
    252                          %      md2=extract(md,area);
    253                          %
    254                          %   Examples:
    255                          %      md2=extract(md,'Domain.exp');
    256                          %      md2=extract(md,md.mask.elementonfloatingice);
    257                          %
    258                          %   See also: EXTRUDE, COLLAPSE
    259 
    260                          %copy model
    261                          md1=md;
    262 
    263                          %some checks
    264                          if ((nargin~=2) | (nargout~=1)),
    265                                  help extract
    266                                  error('extract error message: bad usage');
    267                          end
    268 
    269                          %get check option
    270                          if (nargin==3 & varargin{1}==0),
    271                                  checkoutline=0;
    272                          else
    273                                  checkoutline=1;
    274                          end
    275 
    276                          %get elements that are inside area
    277                          flag_elem=FlagElements(md1,area);
    278                          if ~any(flag_elem),
    279                                  error('extracted model is empty');
    280                          end
    281 
    282                          %kick out all elements with 3 dirichlets
    283                          spc_elem=find(~flag_elem);
    284                          spc_node=sort(unique(md1.mesh.elements(spc_elem,:)));
    285                          flag=ones(md1.mesh.numberofvertices,1);
    286                          flag(spc_node)=0;
    287                          pos=find(sum(flag(md1.mesh.elements),2)==0);
    288                          flag_elem(pos)=0;
    289 
    290                          %extracted elements and nodes lists
    291                          pos_elem=find(flag_elem);
    292                          pos_node=sort(unique(md1.mesh.elements(pos_elem,:)));
    293 
    294                          %keep track of some fields
    295                          numberofvertices1=md1.mesh.numberofvertices;
    296                          numberofelements1=md1.mesh.numberofelements;
    297                          numberofvertices2=length(pos_node);
    298                          numberofelements2=length(pos_elem);
    299                          flag_node=zeros(numberofvertices1,1);
    300                          flag_node(pos_node)=1;
    301 
    302                          %Create Pelem and Pnode (transform old nodes in new nodes and same thing for the elements)
    303                          Pelem=zeros(numberofelements1,1);
    304                          Pelem(pos_elem)=[1:numberofelements2]';
    305                          Pnode=zeros(numberofvertices1,1);
    306                          Pnode(pos_node)=[1:numberofvertices2]';
    307 
    308                          %renumber the elements (some node won't exist anymore)
    309                          elements_1=md1.mesh.elements;
    310                          elements_2=elements_1(pos_elem,:);
    311                          elements_2(:,1)=Pnode(elements_2(:,1));
    312                          elements_2(:,2)=Pnode(elements_2(:,2));
    313                          elements_2(:,3)=Pnode(elements_2(:,3));
    314                          if md1.mesh.dimension==3,
    315                                  elements_2(:,4)=Pnode(elements_2(:,4));
    316                                  elements_2(:,5)=Pnode(elements_2(:,5));
    317                                  elements_2(:,6)=Pnode(elements_2(:,6));
    318                          end
    319 
    320                          %OK, now create the new model !
    321 
    322                          %take every fields from model
    323                          md2=md1;
    324 
    325                          %automatically modify fields
    326 
    327                          %loop over model fields
    328                          model_fields=fields(md1);
    329                          for i=1:length(model_fields),
    330                                  %get field
    331                                  field=md1.(model_fields{i});
    332                                  fieldsize=size(field);
    333                                  if isobject(field), %recursive call
    334                                          object_fields=fields(md1.(model_fields{i}));
    335                                          for j=1:length(object_fields),
    336                                                  %get field
    337                                                  field=md1.(model_fields{i}).(object_fields{j});
    338                                                  fieldsize=size(field);
    339                                                  %size = number of nodes * n
    340                                                  if fieldsize(1)==numberofvertices1
    341                                                          md2.(model_fields{i}).(object_fields{j})=field(pos_node,:);
    342                                                  elseif (fieldsize(1)==numberofvertices1+1)
    343                                                          md2.(model_fields{i}).(object_fields{j})=[field(pos_node,:); field(end,:)];
    344                                                          %size = number of elements * n
    345                                                  elseif fieldsize(1)==numberofelements1
    346                                                          md2.(model_fields{i}).(object_fields{j})=field(pos_elem,:);
    347                                                  end
    348                                          end
    349                                  else
    350                                          %size = number of nodes * n
    351                                          if fieldsize(1)==numberofvertices1
    352                                                  md2.(model_fields{i})=field(pos_node,:);
    353                                          elseif (fieldsize(1)==numberofvertices1+1)
    354                                                  md2.(model_fields{i})=[field(pos_node,:); field(end,:)];
    355                                                  %size = number of elements * n
    356                                          elseif fieldsize(1)==numberofelements1
    357                                                  md2.(model_fields{i})=field(pos_elem,:);
    358                                          end
    359                                  end
    360                          end
    361 
    362                          %modify some specific fields
    363 
    364                          %Mesh
    365                          md2.mesh.numberofelements=numberofelements2;
    366                          md2.mesh.numberofvertices=numberofvertices2;
    367                          md2.mesh.elements=elements_2;
    368 
    369                          %mesh.uppervertex mesh.lowervertex
    370                          if md1.mesh.dimension==3
    371                                  md2.mesh.uppervertex=md1.mesh.uppervertex(pos_node);
    372                                  pos=find(~isnan(md2.mesh.uppervertex));
    373                                  md2.mesh.uppervertex(pos)=Pnode(md2.mesh.uppervertex(pos));
    374 
    375                                  md2.mesh.lowervertex=md1.mesh.lowervertex(pos_node);
    376                                  pos=find(~isnan(md2.mesh.lowervertex));
    377                                  md2.mesh.lowervertex(pos)=Pnode(md2.mesh.lowervertex(pos));
    378 
    379                                  md2.mesh.upperelements=md1.mesh.upperelements(pos_elem);
    380                                  pos=find(~isnan(md2.mesh.upperelements));
    381                                  md2.mesh.upperelements(pos)=Pelem(md2.mesh.upperelements(pos));
    382 
    383                                  md2.mesh.lowerelements=md1.mesh.lowerelements(pos_elem);
    384                                  pos=find(~isnan(md2.mesh.lowerelements));
    385                                  md2.mesh.lowerelements(pos)=Pelem(md2.mesh.lowerelements(pos));
    386                          end
    387 
    388                          %Initial 2d mesh
    389                          if md1.mesh.dimension==3
    390                                  flag_elem_2d=flag_elem(1:md1.mesh.numberofelements2d);
    391                                  pos_elem_2d=find(flag_elem_2d);
    392                                  flag_node_2d=flag_node(1:md1.mesh.numberofvertices2d);
    393                                  pos_node_2d=find(flag_node_2d);
    394 
    395                                  md2.mesh.numberofelements2d=length(pos_elem_2d);
    396                                  md2.mesh.numberofvertices2d=length(pos_node_2d);
    397                                  md2.mesh.elements2d=md1.mesh.elements2d(pos_elem_2d,:);
    398                                  md2.mesh.elements2d(:,1)=Pnode(md2.mesh.elements2d(:,1));
    399                                  md2.mesh.elements2d(:,2)=Pnode(md2.mesh.elements2d(:,2));
    400                                  md2.mesh.elements2d(:,3)=Pnode(md2.mesh.elements2d(:,3));
    401 
    402                                  md2.mesh.x2d=md1.mesh.x(pos_node_2d);
    403                                  md2.mesh.y2d=md1.mesh.y(pos_node_2d);
    404                          end
    405 
    406                          %Edges
    407                          if size(md2.mesh.edges,2)>1, %do not use ~isnan because there are some NaNs...
    408                                  %renumber first two columns
    409                                  pos=find(md2.mesh.edges(:,4)~=-1);
    410                                  md2.mesh.edges(:  ,1)=Pnode(md2.mesh.edges(:,1));
    411                                  md2.mesh.edges(:  ,2)=Pnode(md2.mesh.edges(:,2));
    412                                  md2.mesh.edges(:  ,3)=Pelem(md2.mesh.edges(:,3));
    413                                  md2.mesh.edges(pos,4)=Pelem(md2.mesh.edges(pos,4));
    414                                  %remove edges when the 2 vertices are not in the domain.
    415                                  md2.mesh.edges=md2.mesh.edges(find(md2.mesh.edges(:,1) & md2.mesh.edges(:,2)),:);
    416                                  %Replace all zeros by -1 in the last two columns;
    417                                  pos=find(md2.mesh.edges(:,3)==0);
    418                                  md2.mesh.edges(pos,3)=-1;
    419                                  pos=find(md2.mesh.edges(:,4)==0);
    420                                  md2.mesh.edges(pos,4)=-1;
    421                                  %Invert -1 on the third column with last column (Also invert first two columns!!)
    422                                  pos=find(md2.mesh.edges(:,3)==-1);
    423                                  md2.mesh.edges(pos,3)=md2.mesh.edges(pos,4);
    424                                  md2.mesh.edges(pos,4)=-1;
    425                                  values=md2.mesh.edges(pos,2);
    426                                  md2.mesh.edges(pos,2)=md2.mesh.edges(pos,1);
    427                                  md2.mesh.edges(pos,1)=values;
    428                                  %Finally remove edges that do not belong to any element
    429                                  pos=find(md2.mesh.edges(:,3)==-1 & md2.mesh.edges(:,4)==-1);
    430                                  md2.mesh.edges(pos,:)=[];
    431                          end
    432 
    433                          %Penalties
    434                          if ~isnan(md2.diagnostic.vertex_pairing),
    435                                  for i=1:size(md1.diagnostic.vertex_pairing,1);
    436                                          md2.diagnostic.vertex_pairing(i,:)=Pnode(md1.diagnostic.vertex_pairing(i,:));
    437                                  end
    438                                  md2.diagnostic.vertex_pairing=md2.diagnostic.vertex_pairing(find(md2.diagnostic.vertex_pairing(:,1)),:);
    439                          end
    440                          if ~isnan(md2.prognostic.vertex_pairing),
    441                                  for i=1:size(md1.prognostic.vertex_pairing,1);
    442                                          md2.prognostic.vertex_pairing(i,:)=Pnode(md1.prognostic.vertex_pairing(i,:));
    443                                  end
    444                                  md2.prognostic.vertex_pairing=md2.prognostic.vertex_pairing(find(md2.prognostic.vertex_pairing(:,1)),:);
    445                          end
    446 
    447                          %recreate segments
    448                          if md1.mesh.dimension==2
    449                                  md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices);
    450                                  md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity);
    451                                  md2.mesh.segments=contourenvelope(md2);
    452                                  md2.mesh.vertexonboundary=zeros(numberofvertices2,1); md2.mesh.vertexonboundary(md2.mesh.segments(:,1:2))=1;
    453                          else
    454                                  %First do the connectivity for the contourenvelope in 2d
    455                                  md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements2d,md2.mesh.numberofvertices2d);
    456                                  md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements2d,md2.mesh.vertexconnectivity);
    457                                  md2.mesh.segments=contourenvelope(md2);
    458                                  md2.mesh.vertexonboundary=zeros(numberofvertices2/md2.mesh.numberoflayers,1); md2.mesh.vertexonboundary(md2.mesh.segments(:,1:2))=1;
    459                                  md2.mesh.vertexonboundary=repmat(md2.mesh.vertexonboundary,md2.mesh.numberoflayers,1);
    460                                  %Then do it for 3d as usual
    461                                  md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices);
    462                                  md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity);
    463                          end
    464 
    465                          %Boundary conditions: Dirichlets on new boundary
    466                          %Catch the elements that have not been extracted
    467                          orphans_elem=find(~flag_elem);
    468                          orphans_node=unique(md1.mesh.elements(orphans_elem,:))';
    469                          %Figure out which node are on the boundary between md2 and md1
    470                          nodestoflag1=intersect(orphans_node,pos_node);
    471                          nodestoflag2=Pnode(nodestoflag1);
    472                          if numel(md1.diagnostic.spcvx)>1 & numel(md1.diagnostic.spcvy)>2 & numel(md1.diagnostic.spcvz)>2,
    473                                  if numel(md1.inversion.vx_obs)>1 & numel(md1.inversion.vy_obs)>1
    474                                          md2.diagnostic.spcvx(nodestoflag2)=md2.inversion.vx_obs(nodestoflag2);
    475                                          md2.diagnostic.spcvy(nodestoflag2)=md2.inversion.vy_obs(nodestoflag2);
    476                                  else
    477                                          md2.diagnostic.spcvx(nodestoflag2)=NaN;
    478                                          md2.diagnostic.spcvy(nodestoflag2)=NaN;
    479                                          disp(' ')
    480                                          disp('!! extract warning: spc values should be checked !!')
    481                                          disp(' ')
    482                                  end
    483                                  %put 0 for vz
    484                                  md2.diagnostic.spcvz(nodestoflag2)=0;
    485                          end
    486                          if ~isnan(md1.thermal.spctemperature),
    487                                  md2.thermal.spctemperature(nodestoflag2,1)=1;
    488                          end
    489 
    490                          %Diagnostic
    491                          if ~isnan(md2.diagnostic.icefront)
    492                                  md2.diagnostic.icefront(:,1)=Pnode(md1.diagnostic.icefront(:,1));
    493                                  md2.diagnostic.icefront(:,2)=Pnode(md1.diagnostic.icefront(:,2));
    494                                  md2.diagnostic.icefront(:,end-1)=Pelem(md1.diagnostic.icefront(:,end-1));
    495                                  if md1.mesh.dimension==3
    496                                          md2.diagnostic.icefront(:,3)=Pnode(md1.diagnostic.icefront(:,3));
    497                                          md2.diagnostic.icefront(:,4)=Pnode(md1.diagnostic.icefront(:,4));
    498                                  end
    499                                  md2.diagnostic.icefront=md2.diagnostic.icefront(find(md2.diagnostic.icefront(:,1) & md2.diagnostic.icefront(:,2) & md2.diagnostic.icefront(:,end)),:);
    500                          end
    501 
    502                          %Results fields
    503                          if isstruct(md1.results),
    504                                  md2.results=struct();
    505                                  solutionfields=fields(md1.results);
    506                                  for i=1:length(solutionfields),
    507                                          %get subfields
    508                                          solutionsubfields=fields(md1.results.(solutionfields{i}));
    509                                          for j=1:length(solutionsubfields),
    510                                                  field=md1.results.(solutionfields{i}).(solutionsubfields{j});
    511                                                  if length(field)==numberofvertices1,
    512                                                          md2.results.(solutionfields{i}).(solutionsubfields{j})=field(pos_node);
    513                                                  elseif length(field)==numberofelements1,
    514                                                          md2.results.(solutionfields{i}).(solutionsubfields{j})=field(pos_elem);
    515                                                  else
    516                                                          md2.results.(solutionfields{i}).(solutionsubfields{j})=field;
    517                                                  end
    518                                          end
    519                                  end
    520                          end
    521 
    522                          %Keep track of pos_node and pos_elem
    523                          md2.mesh.extractedvertices=pos_node;
    524                          md2.mesh.extractedelements=pos_elem;
    525                  end % }}}
    526                  function md = extrude(md,varargin) % {{{
    527                          %EXTRUDE - vertically extrude a 2d mesh
    528                          %
    529                          %   vertically extrude a 2d mesh and create corresponding 3d mesh.
    530                          %   The vertical distribution can:
    531                          %    - follow a polynomial law
    532                          %    - follow two polynomial laws, one for the lower part and one for the upper part of the mesh
    533                          %    - be discribed by a list of coefficients (between 0 and 1)
    534                          %   
    535                          %
    536                          %   Usage:
    537                          %      md=extrude(md,numlayers,extrusionexponent);
    538                          %      md=extrude(md,numlayers,lowerexponent,upperexponent);
    539                          %      md=extrude(md,listofcoefficients);
    540                          %
    541                          %   Example:
    542                          %      md=extrude(md,8,3);
    543                          %      md=extrude(md,8,3,2);
    544                          %      md=extrude(md,[0 0.2 0.5 0.7 0.9 0.95 1]);
    545                          %
    546                          %   See also: MODELEXTRACT, COLLAPSE
    547 
    548                          %some checks on list of arguments
    549                          if ((nargin>4) | (nargin<2) | (nargout~=1)),
    550                                  help extrude;
    551                                  error('extrude error message');
    552                          end
    553 
    554                          %Extrude the mesh
    555                          if nargin==2, %list of coefficients
    556                                  clist=varargin{1};
    557                                  if any(clist<0) | any(clist>1),
    558                                          error('extrusioncoefficients must be between 0 and 1');
    559                                  end
    560                                  extrusionlist=sort(unique([clist(:);0;1]));
    561                                  numlayers=length(extrusionlist);
    562                          elseif nargin==3, %one polynomial law
    563                                  if varargin{2}<=0,
    564                                          help extrude;
    565                                          error('extrusionexponent must be >=0');
    566                                  end
    567                                  numlayers=varargin{1};
    568                                  extrusionlist=((0:1:numlayers-1)/(numlayers-1)).^varargin{2};
    569                          elseif nargin==4, %two polynomial laws
    570                                  numlayers=varargin{1};
    571                                  lowerexp=varargin{2};
    572                                  upperexp=varargin{3};
    573 
    574                                  if varargin{2}<=0 | varargin{3}<=0,
    575                                          help extrude;
    576                                          error('lower and upper extrusionexponents must be >=0');
    577                                  end
    578 
    579                                  lowerextrusionlist=[(0:2/(numlayers-1):1).^lowerexp]/2;
    580                                  upperextrusionlist=[(0:2/(numlayers-1):1).^upperexp]/2;
    581                                  extrusionlist=sort(unique([lowerextrusionlist 1-upperextrusionlist]));
    582 
    583                          end
    584 
    585                          if numlayers<2,
    586                                  error('number of layers should be at least 2');
    587                          end
    588                          if md.mesh.dimension==3,
    589                                  error('Cannot extrude a 3d mesh (extrude cannot be called more than once)');
    590                          end
    591 
    592                          %Initialize with the 2d mesh
    593                          x3d=[];
    594                          y3d=[];
    595                          z3d=[];  %the lower node is on the bed
    596                          thickness3d=md.geometry.thickness; %thickness and bed for these nodes
    597                          bed3d=md.geometry.bed;
    598 
    599                          %Create the new layers
    600                          for i=1:numlayers,
    601                                  x3d=[x3d; md.mesh.x];
    602                                  y3d=[y3d; md.mesh.y];
    603                                  %nodes are distributed between bed and surface accordingly to the given exponent
    604                                  z3d=[z3d; bed3d+thickness3d*extrusionlist(i)];
    605                          end
    606                          number_nodes3d=size(x3d,1); %number of 3d nodes for the non extruded part of the mesh
    607 
    608                          %Extrude elements
    609                          elements3d=[];
    610                          for i=1:numlayers-1,
    611                                  elements3d=[elements3d;[md.mesh.elements+(i-1)*md.mesh.numberofvertices md.mesh.elements+i*md.mesh.numberofvertices]]; %Create the elements of the 3d mesh for the non extruded part
    612                          end
    613                          number_el3d=size(elements3d,1); %number of 3d nodes for the non extruded part of the mesh
    614 
    615                          %Keep a trace of lower and upper nodes
    616                          mesh.lowervertex=NaN*ones(number_nodes3d,1);
    617                          mesh.uppervertex=NaN*ones(number_nodes3d,1);
    618                          mesh.lowervertex(md.mesh.numberofvertices+1:end)=1:(numlayers-1)*md.mesh.numberofvertices;
    619                          mesh.uppervertex(1:(numlayers-1)*md.mesh.numberofvertices)=md.mesh.numberofvertices+1:number_nodes3d;
    620                          md.mesh.lowervertex=mesh.lowervertex;
    621                          md.mesh.uppervertex=mesh.uppervertex;
    622 
    623                          %same for lower and upper elements
    624                          mesh.lowerelements=NaN*ones(number_el3d,1);
    625                          mesh.upperelements=NaN*ones(number_el3d,1);
    626                          mesh.lowerelements(md.mesh.numberofelements+1:end)=1:(numlayers-2)*md.mesh.numberofelements;
    627                          mesh.upperelements(1:(numlayers-2)*md.mesh.numberofelements)=md.mesh.numberofelements+1:(numlayers-1)*md.mesh.numberofelements;
    628                          md.mesh.lowerelements=mesh.lowerelements;
    629                          md.mesh.upperelements=mesh.upperelements;
    630 
    631                          %Save old mesh
    632                          md.mesh.x2d=md.mesh.x;
    633                          md.mesh.y2d=md.mesh.y;
    634                          md.mesh.elements2d=md.mesh.elements;
    635                          md.mesh.numberofelements2d=md.mesh.numberofelements;
    636                          md.mesh.numberofvertices2d=md.mesh.numberofvertices;
    637 
    638                          %Update mesh type
    639                          md.mesh.dimension=3;
    640 
    641                          %Build global 3d mesh
    642                          md.mesh.elements=elements3d;
    643                          md.mesh.x=x3d;
    644                          md.mesh.y=y3d;
    645                          md.mesh.z=z3d;
    646                          md.mesh.numberofelements=number_el3d;
    647                          md.mesh.numberofvertices=number_nodes3d;
    648                          md.mesh.numberoflayers=numlayers;
    649 
    650                          %Ok, now deal with the other fields from the 2d mesh:
    651 
    652                          %lat long
    653                          md.mesh.lat=project3d(md,'vector',md.mesh.lat,'type','node');
    654                          md.mesh.long=project3d(md,'vector',md.mesh.long,'type','node');
    655 
    656                          %drag coefficient is limited to nodes that are on the bedrock.
    657                          md.friction.coefficient=project3d(md,'vector',md.friction.coefficient,'type','node','layer',1);
    658 
    659                          %p and q (same deal, except for element that are on the bedrock: )
    660                          md.friction.p=project3d(md,'vector',md.friction.p,'type','element');
    661                          md.friction.q=project3d(md,'vector',md.friction.q,'type','element');
    662 
    663                          %observations
    664                          md.inversion.vx_obs=project3d(md,'vector',md.inversion.vx_obs,'type','node');
    665                          md.inversion.vy_obs=project3d(md,'vector',md.inversion.vy_obs,'type','node');
    666                          md.inversion.vel_obs=project3d(md,'vector',md.inversion.vel_obs,'type','node');
    667                          md.surfaceforcings.mass_balance=project3d(md,'vector',md.surfaceforcings.mass_balance,'type','node');
    668                          md.surfaceforcings.precipitation=project3d(md,'vector',md.surfaceforcings.precipitation,'type','node');
    669                          md.balancethickness.thickening_rate=project3d(md,'vector',md.balancethickness.thickening_rate,'type','node');
    670                          md.surfaceforcings.monthlytemperatures=project3d(md,'vector',md.surfaceforcings.monthlytemperatures,'type','node');
    671 
    672                          %results
    673                          if ~isnan(md.initialization.vx),md.initialization.vx=project3d(md,'vector',md.initialization.vx,'type','node');end;
    674                          if ~isnan(md.initialization.vy),md.initialization.vy=project3d(md,'vector',md.initialization.vy,'type','node');end;
    675                          if ~isnan(md.initialization.vz),md.initialization.vz=project3d(md,'vector',md.initialization.vz,'type','node');end;
    676                          if ~isnan(md.initialization.vel),md.initialization.vel=project3d(md,'vector',md.initialization.vel,'type','node');end;
    677                          if ~isnan(md.initialization.temperature),md.initialization.temperature=project3d(md,'vector',md.initialization.temperature,'type','node');end;
    678                          if ~isnan(md.initialization.waterfraction),md.initialization.waterfraction=project3d(md,'vector',md.initialization.waterfraction,'type','node');end;
    679 
    680                          %bedinfo and surface info
    681                          md.mesh.elementonbed=project3d(md,'vector',ones(md.mesh.numberofelements2d,1),'type','element','layer',1);
    682                          md.mesh.elementonsurface=project3d(md,'vector',ones(md.mesh.numberofelements2d,1),'type','element','layer',md.mesh.numberoflayers-1);
    683                          md.mesh.vertexonbed=project3d(md,'vector',ones(md.mesh.numberofvertices2d,1),'type','node','layer',1);
    684                          md.mesh.vertexonsurface=project3d(md,'vector',ones(md.mesh.numberofvertices2d,1),'type','node','layer',md.mesh.numberoflayers);
    685 
    686                          %elementstype
    687                          if ~isnan(md.flowequation.element_equation)
    688                                  oldelements_type=md.flowequation.element_equation;
    689                                  md.flowequation.element_equation=zeros(number_el3d,1);
    690                                  md.flowequation.element_equation=project3d(md,'vector',oldelements_type,'type','element');
    691                          end
    692 
    693                          %verticestype
    694                          if ~isnan(md.flowequation.vertex_equation)
    695                                  oldvertices_type=md.flowequation.vertex_equation;
    696                                  md.flowequation.vertex_equation=zeros(number_nodes3d,1);
    697                                  md.flowequation.vertex_equation=project3d(md,'vector',oldvertices_type,'type','node');
    698                          end
    699                          md.flowequation.bordermacayeal=project3d(md,'vector',md.flowequation.bordermacayeal,'type','node');
    700                          md.flowequation.borderpattyn=project3d(md,'vector',md.flowequation.borderpattyn,'type','node');
    701                          md.flowequation.borderstokes=project3d(md,'vector',md.flowequation.borderstokes,'type','node');
    702 
    703                          %boundary conditions
    704                          md.diagnostic.spcvx=project3d(md,'vector',md.diagnostic.spcvx,'type','node');
    705                          md.diagnostic.spcvy=project3d(md,'vector',md.diagnostic.spcvy,'type','node');
    706                          md.diagnostic.spcvz=project3d(md,'vector',md.diagnostic.spcvz,'type','node');
    707                          md.thermal.spctemperature=project3d(md,'vector',md.thermal.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',NaN);
    708                          md.prognostic.spcthickness=project3d(md,'vector',md.prognostic.spcthickness,'type','node');
    709                          md.balancethickness.spcthickness=project3d(md,'vector',md.balancethickness.spcthickness,'type','node');
    710                          md.diagnostic.referential=project3d(md,'vector',md.diagnostic.referential,'type','node');
    711 
    712                          %in 3d, pressureload: [node1 node2 node3 node4 element]
    713                          pressureload_layer1=[md.diagnostic.icefront(:,1:2)  md.diagnostic.icefront(:,2)+md.mesh.numberofvertices2d  md.diagnostic.icefront(:,1)+md.mesh.numberofvertices2d  md.diagnostic.icefront(:,3:4)]; %Add two columns on the first layer
    714                          pressureload=[];
    715                          for i=1:numlayers-1,
    716                                  pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d pressureload_layer1(:,6)];
    717                          end
    718                          md.diagnostic.icefront=pressureload;
    719 
    720                          %connectivity
    721                          md.mesh.elementconnectivity=repmat(md.mesh.elementconnectivity,numlayers-1,1);
    722                          md.mesh.elementconnectivity(find(md.mesh.elementconnectivity==0))=NaN;
    723                          for i=2:numlayers-1,
    724                                  md.mesh.elementconnectivity((i-1)*md.mesh.numberofelements2d+1:(i)*md.mesh.numberofelements2d,:)...
    725                                          =md.mesh.elementconnectivity((i-1)*md.mesh.numberofelements2d+1:(i)*md.mesh.numberofelements2d,:)+md.mesh.numberofelements2d;
    726                          end
    727                          md.mesh.elementconnectivity(find(isnan(md.mesh.elementconnectivity)))=0;
    728 
    729                          %materials
    730                          md.materials.rheology_B=project3d(md,'vector',md.materials.rheology_B,'type','node');
    731                          md.materials.rheology_n=project3d(md,'vector',md.materials.rheology_n,'type','element');
    732                          if isa(md.materials,'matdamageice')
    733                                  md.materials.rheology_Z=project3d(md,'vector',md.materials.rheology_Z,'type','node');
    734                          end
    735 
    736                          %parameters
    737                          md.geometry.surface=project3d(md,'vector',md.geometry.surface,'type','node');
    738                          md.geometry.thickness=project3d(md,'vector',md.geometry.thickness,'type','node');
    739                          md.geometry.hydrostatic_ratio=project3d(md,'vector',md.geometry.hydrostatic_ratio,'type','node');
    740                          md.geometry.bed=project3d(md,'vector',md.geometry.bed,'type','node');
    741                          md.geometry.bathymetry=project3d(md,'vector',md.geometry.bathymetry,'type','node');
    742                          md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node');
    743                          md.mask.elementonfloatingice=project3d(md,'vector',md.mask.elementonfloatingice,'type','element');
    744                          md.mask.vertexonfloatingice=project3d(md,'vector',md.mask.vertexonfloatingice,'type','node');
    745                          md.mask.elementongroundedice=project3d(md,'vector',md.mask.elementongroundedice,'type','element');
    746                          md.mask.vertexongroundedice=project3d(md,'vector',md.mask.vertexongroundedice,'type','node');
    747                          md.mask.elementonwater=project3d(md,'vector',md.mask.elementonwater,'type','element');
    748                          md.mask.vertexonwater=project3d(md,'vector',md.mask.vertexonwater,'type','node');
    749                          if ~isnan(md.inversion.cost_functions_coefficients),md.inversion.cost_functions_coefficients=project3d(md,'vector',md.inversion.cost_functions_coefficients,'type','node');end;
    750                          if ~isnan(md.inversion.min_parameters),md.inversion.min_parameters=project3d(md,'vector',md.inversion.min_parameters,'type','node');end;
    751                          if ~isnan(md.inversion.max_parameters),md.inversion.max_parameters=project3d(md,'vector',md.inversion.max_parameters,'type','node');end;
    752                          if ~isnan(md.qmu.partition),md.qmu.partition=project3d(md,'vector',md.qmu.partition','type','node');end
    753                          if(md.surfaceforcings.isdelta18o),md.surfaceforcings.temperatures_lgm=project3d(md,'vector',md.surfaceforcings.temperatures_lgm,'type','node');end
    754                          if(md.surfaceforcings.isdelta18o),md.surfaceforcings.temperatures_presentday=project3d(md,'vector',md.surfaceforcings.temperatures_presentday,'type','node');end
    755                          if(md.surfaceforcings.isdelta18o),md.surfaceforcings.precipitations_presentday=project3d(md,'vector',md.surfaceforcings.precipitations_presentday,'type','node');end
    756 
    757                          %Put lithostatic pressure if there is an existing pressure
    758                          if ~isnan(md.initialization.pressure),
    759                                  md.initialization.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z);
    760                          end
    761 
    762                          %special for thermal modeling:
    763                          md.basalforcings.melting_rate=project3d(md,'vector',md.basalforcings.melting_rate,'type','node','layer',1);
    764                          if ~isnan(md.basalforcings.geothermalflux)
    765                                  md.basalforcings.geothermalflux=project3d(md,'vector',md.basalforcings.geothermalflux,'type','node','layer',1); %bedrock only gets geothermal flux
    766                          end
    767 
    768                          %increase connectivity if less than 25:
    769                          if md.mesh.average_vertex_connectivity<=25,
    770                                  md.mesh.average_vertex_connectivity=100;
    771                          end
     7        properties (SetAccess=public) %Model fields
     8                % {{{
     9                %Careful here: no other class should be used as default value this is a bug of matlab
     10                mesh             = 0;
     11                mask             = 0;
     12
     13                geometry         = 0;
     14                constants        = 0;
     15                surfaceforcings  = 0;
     16                basalforcings    = 0;
     17                materials        = 0;
     18                friction         = 0;
     19                flowequation     = 0;
     20                timestepping     = 0;
     21                initialization   = 0;
     22                rifts            = 0;
     23
     24                debug            = 0;
     25                verbose          = 0;
     26                settings         = 0;
     27                solver           = 0;
     28                cluster          = 0;
     29
     30                balancethickness = 0;
     31                diagnostic       = 0;
     32                groundingline    = 0;
     33                hydrology        = 0;
     34                prognostic       = 0;
     35                thermal          = 0;
     36                steadystate      = 0;
     37                transient        = 0;
     38
     39                autodiff         = 0;
     40                flaim            = 0;
     41                inversion        = 0;
     42                qmu              = 0;
     43
     44                results          = 0;
     45                radaroverlay     = 0;
     46                miscellaneous    = 0;
     47                private          = 0;
     48
     49                %}}}
     50        end
     51        methods (Static)
     52                function md = loadobj(md) % {{{
     53                        % This function is directly called by matlab when a model object is
     54                        % loaded. If the input is a struct it is an old version of model and
     55                        % old fields must be recovered (make sure they are in the deprecated
     56                        % model properties)
     57
     58                        if verLessThan('matlab','7.9'),
     59                                disp('Warning: your matlab version is old and there is a risk that load does not work correctly');
     60                                disp('         if the model is not loaded correctly, rename temporarily loadobj so that matlab does not use it');
     61
     62                                % This is a Matlab bug: all the fields of md have their default value
     63                                % Example of error message:
     64                                % Warning: Error loading an object of class 'model':
     65                                % Undefined function or method 'exist' for input arguments of type 'cell'
     66                                %
     67                                % This has been fixed in MATLAB 7.9 (R2009b) and later versions
     68                        end
     69
     70                        if isstruct(md)
     71                                disp('Recovering model object from a previous version');
     72                                md = structtomodel(model,md);
     73                        end
     74
     75                        %2012 August 4th
     76                        if isa(md.materials,'materials'),
     77                                disp('Recovering old materials');
     78                                if numel(md.materials.rheology_Z)==1 & isnan(md.materials.rheology_Z),
     79                                        md.materials=matice(md.materials);
     80                                else
     81                                        md.materials=matdamageice(md.materials);
     82                                end
     83                        end
     84                        %2012 June 28th
     85                        if sum(sum(isnan(md.mesh.edges)))>0
     86                                disp('Update model edges from previous version');
     87                                md.mesh.edges(isnan(md.mesh.edges))=-1;
     88                        end
     89
     90                end% }}}
     91        end
     92        methods
     93                function md = model(varargin) % {{{
     94
     95                        switch nargin
     96                                case 0
     97                                        md=setdefaultparameters(md);
     98                                otherwise
     99                                        error('model constructor error message: 0 of 1 argument only in input.');
     100                                end
     101                end
     102                %}}}
     103                function md = checkmessage(md,string) % {{{
     104                        if(nargout~=1) error('wrong usage, model must be an output'); end
     105                        disp(['model not consistent: ' string]);
     106                        md.private.isconsistent=false;
     107                end
     108                %}}}
     109                function md = collapse(md)% {{{
     110                        %COLLAPSE - collapses a 3d mesh into a 2d mesh
     111                        %
     112                        %   This routine collapses a 3d model into a 2d model
     113                        %   and collapses all the fileds of the 3d model by
     114                        %   taking their depth-averaged values
     115                        %
     116                        %   Usage:
     117                        %      md=collapse(md)
     118                        %
     119                        %   See also: EXTRUDE, MODELEXTRACT
     120
     121                        %Check that the model is really a 3d model
     122                        if ~md.mesh.dimension==3,
     123                                error('collapse error message: only 3d mesh can be collapsed')
     124                        end
     125
     126                        %Start with changing alle the fields from the 3d mesh
     127
     128                        %drag is limited to nodes that are on the bedrock.
     129                        md.friction.coefficient=project2d(md,md.friction.coefficient,1);
     130
     131                        %p and q (same deal, except for element that are on the bedrock: )
     132                        md.friction.p=project2d(md,md.friction.p,1);
     133                        md.friction.q=project2d(md,md.friction.q,1);
     134
     135                        %observations
     136                        if ~isnan(md.inversion.vx_obs), md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers); end;
     137                        if ~isnan(md.inversion.vy_obs), md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers); end;
     138                        if ~isnan(md.inversion.vel_obs), md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers); end;
     139                        if ~isnan(md.inversion.cost_functions_coefficients), md.inversion.cost_functions_coefficients=project2d(md,md.inversion.cost_functions_coefficients,md.mesh.numberoflayers); end;
     140                        if numel(md.inversion.min_parameters)>1, md.inversion.min_parameters=project2d(md,md.inversion.min_parameters,md.mesh.numberoflayers); end;
     141                        if numel(md.inversion.max_parameters)>1, md.inversion.max_parameters=project2d(md,md.inversion.max_parameters,md.mesh.numberoflayers); end;
     142                        if ~isnan(md.surfaceforcings.mass_balance),
     143                                md.surfaceforcings.mass_balance=project2d(md,md.surfaceforcings.mass_balance,md.mesh.numberoflayers);
     144                        end;
     145                        if ~isnan(md.balancethickness.thickening_rate), md.balancethickness.thickening_rate=project2d(md,md.balancethickness.thickening_rate,md.mesh.numberoflayers); end;
     146
     147                        %results
     148                        if ~isnan(md.initialization.vx),md.initialization.vx=DepthAverage(md,md.initialization.vx);end;
     149                        if ~isnan(md.initialization.vy),md.initialization.vy=DepthAverage(md,md.initialization.vy);end;
     150                        if ~isnan(md.initialization.vz),md.initialization.vz=DepthAverage(md,md.initialization.vz);end;
     151                        if ~isnan(md.initialization.vel),md.initialization.vel=DepthAverage(md,md.initialization.vel);end;
     152                        if ~isnan(md.initialization.temperature),md.initialization.temperature=DepthAverage(md,md.initialization.temperature);end;
     153
     154                        %bedinfo and surface info
     155                        md.mesh.elementonbed=ones(md.mesh.numberofelements2d,1);
     156                        md.mesh.elementonsurface=ones(md.mesh.numberofelements2d,1);
     157                        md.mesh.vertexonbed=ones(md.mesh.numberofvertices2d,1);
     158                        md.mesh.vertexonsurface=ones(md.mesh.numberofvertices2d,1);
     159
     160                        %elementstype
     161                        if ~isnan(md.flowequation.element_equation)
     162                                md.flowequation.element_equation=project2d(md,md.flowequation.element_equation,1);
     163                                md.flowequation.vertex_equation=project2d(md,md.flowequation.vertex_equation,1);
     164                                md.flowequation.bordermacayeal=project2d(md,md.flowequation.bordermacayeal,1);
     165                                md.flowequation.borderpattyn=project2d(md,md.flowequation.borderpattyn,1);
     166                                md.flowequation.borderstokes=project2d(md,md.flowequation.borderstokes,1);
     167                        end     
     168
     169                        %boundary conditions
     170                        md.diagnostic.spcvx=project2d(md,md.diagnostic.spcvx,md.mesh.numberoflayers);
     171                        md.diagnostic.spcvy=project2d(md,md.diagnostic.spcvy,md.mesh.numberoflayers);
     172                        md.diagnostic.spcvz=project2d(md,md.diagnostic.spcvz,md.mesh.numberoflayers);
     173                        md.diagnostic.referential=project2d(md,md.diagnostic.referential,md.mesh.numberoflayers);
     174                        md.prognostic.spcthickness=project2d(md,md.prognostic.spcthickness,md.mesh.numberoflayers);
     175                        md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers);
     176
     177                        %Extrusion of Neumann BC
     178                        if ~isnan(md.diagnostic.icefront),
     179                                numberofneumann2d=size(md.diagnostic.icefront,1)/(md.mesh.numberoflayers-1);
     180                                md.diagnostic.icefront=[md.diagnostic.icefront(1:numberofneumann2d,1:2) md.diagnostic.icefront(1:numberofneumann2d,5:6)]; %Add two columns on the first layer
     181                        end
     182
     183                        %materials
     184                        md.materials.rheology_B=DepthAverage(md,md.materials.rheology_B);
     185                        md.materials.rheology_n=project2d(md,md.materials.rheology_n,1);
     186                        if isa(md.materials,'matdamageice')
     187                                md.materials.rheology_Z=DepthAverage(md,md.materials.rheology_Z);
     188                        end
     189
     190                        %special for thermal modeling:
     191                        md.basalforcings.melting_rate=project2d(md,md.basalforcings.melting_rate,1);
     192                        md.basalforcings.geothermalflux=project2d(md,md.basalforcings.geothermalflux,1); %bedrock only gets geothermal flux
     193
     194                        %update of connectivity matrix
     195                        md.mesh.average_vertex_connectivity=25;
     196
     197                        %Collapse the mesh
     198                        nodes2d=md.mesh.numberofvertices2d;
     199                        elements2d=md.mesh.numberofelements2d;
     200
     201                        %parameters
     202                        md.geometry.surface=project2d(md,md.geometry.surface,1);
     203                        md.geometry.thickness=project2d(md,md.geometry.thickness,1);
     204                        md.geometry.bed=project2d(md,md.geometry.bed,1);
     205                        md.geometry.bathymetry=project2d(md,md.geometry.bathymetry,1);
     206                        md.mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1);
     207                        md.mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1);
     208                        md.mask.elementonfloatingice=project2d(md,md.mask.elementonfloatingice,1);
     209                        md.mask.vertexonfloatingice=project2d(md,md.mask.vertexonfloatingice,1);
     210                        md.mask.elementongroundedice=project2d(md,md.mask.elementongroundedice,1);
     211                        md.mask.vertexongroundedice=project2d(md,md.mask.vertexongroundedice,1);
     212                        md.mask.elementonwater=project2d(md,md.mask.elementonwater,1);
     213                        md.mask.vertexonwater=project2d(md,md.mask.vertexonwater,1);
     214
     215                        %lat long
     216                        if numel(md.mesh.lat) ==md.mesh.numberofvertices,  md.mesh.lat=project2d(md,md.mesh.lat,1); end
     217                        if numel(md.mesh.long)==md.mesh.numberofvertices, md.mesh.long=project2d(md,md.mesh.long,1); end
     218
     219                        %Initialize with the 2d mesh
     220                        md.mesh.x=md.mesh.x2d;
     221                        md.mesh.y=md.mesh.y2d;
     222                        md.mesh.z=zeros(size(md.mesh.x2d));
     223                        md.mesh.numberofvertices=md.mesh.numberofvertices2d;
     224                        md.mesh.numberofelements=md.mesh.numberofelements2d;
     225                        md.mesh.elements=md.mesh.elements2d;
     226
     227                        %Keep a trace of lower and upper nodes
     228                        md.mesh.lowervertex=NaN;
     229                        md.mesh.uppervertex=NaN;
     230                        md.mesh.lowerelements=NaN;
     231                        md.mesh.upperelements=NaN;
     232
     233                        %Remove old mesh
     234                        md.mesh.x2d=NaN;
     235                        md.mesh.y2d=NaN;
     236                        md.mesh.elements2d=NaN;
     237                        md.mesh.numberofelements2d=md.mesh.numberofelements;
     238                        md.mesh.numberofvertices2d=md.mesh.numberofvertices;
     239                        md.mesh.numberoflayers=0;
     240
     241                        %Update mesh type
     242                        md.mesh.dimension=2;
     243                end % }}}
     244                function md2 = extract(md,area) % {{{
     245                        %extract - extract a model according to an Argus contour or flag list
     246                        %
     247                        %   This routine extracts a submodel from a bigger model with respect to a given contour
     248                        %   md must be followed by the corresponding exp file or flags list
     249                        %   It can either be a domain file (argus type, .exp extension), or an array of element flags.
     250                        %   If user wants every element outside the domain to be
     251                        %   extract2d, add '~' to the name of the domain file (ex: '~Pattyn.exp');
     252                        %   an empty string '' will be considered as an empty domain
     253                        %   a string 'all' will be considered as the entire domain
     254                        %
     255                        %   Usage:
     256                        %      md2=extract(md,area);
     257                        %
     258                        %   Examples:
     259                        %      md2=extract(md,'Domain.exp');
     260                        %      md2=extract(md,md.mask.elementonfloatingice);
     261                        %
     262                        %   See also: EXTRUDE, COLLAPSE
     263
     264                        %copy model
     265                        md1=md;
     266
     267                        %some checks
     268                        if ((nargin~=2) | (nargout~=1)),
     269                                help extract
     270                                error('extract error message: bad usage');
     271                        end
     272
     273                        %get elements that are inside area
     274                        flag_elem=FlagElements(md1,area);
     275                        if ~any(flag_elem),
     276                                error('extracted model is empty');
     277                        end
     278
     279                        %kick out all elements with 3 dirichlets
     280                        spc_elem=find(~flag_elem);
     281                        spc_node=sort(unique(md1.mesh.elements(spc_elem,:)));
     282                        flag=ones(md1.mesh.numberofvertices,1);
     283                        flag(spc_node)=0;
     284                        pos=find(sum(flag(md1.mesh.elements),2)==0);
     285                        flag_elem(pos)=0;
     286
     287                        %extracted elements and nodes lists
     288                        pos_elem=find(flag_elem);
     289                        pos_node=sort(unique(md1.mesh.elements(pos_elem,:)));
     290
     291                        %keep track of some fields
     292                        numberofvertices1=md1.mesh.numberofvertices;
     293                        numberofelements1=md1.mesh.numberofelements;
     294                        numberofvertices2=length(pos_node);
     295                        numberofelements2=length(pos_elem);
     296                        flag_node=zeros(numberofvertices1,1);
     297                        flag_node(pos_node)=1;
     298
     299                        %Create Pelem and Pnode (transform old nodes in new nodes and same thing for the elements)
     300                        Pelem=zeros(numberofelements1,1);
     301                        Pelem(pos_elem)=[1:numberofelements2]';
     302                        Pnode=zeros(numberofvertices1,1);
     303                        Pnode(pos_node)=[1:numberofvertices2]';
     304
     305                        %renumber the elements (some nodes won't exist anymore)
     306                        elements_1=md1.mesh.elements;
     307                        elements_2=elements_1(pos_elem,:);
     308                        elements_2(:,1)=Pnode(elements_2(:,1));
     309                        elements_2(:,2)=Pnode(elements_2(:,2));
     310                        elements_2(:,3)=Pnode(elements_2(:,3));
     311                        if md1.mesh.dimension==3,
     312                                elements_2(:,4)=Pnode(elements_2(:,4));
     313                                elements_2(:,5)=Pnode(elements_2(:,5));
     314                                elements_2(:,6)=Pnode(elements_2(:,6));
     315                        end
     316
     317                        %OK, now create the new model!
     318
     319                        %take every field from model
     320                        md2=md1;
     321
     322                        %automatically modify fields
     323
     324                        %loop over model fields
     325                        model_fields=fields(md1);
     326                        for i=1:length(model_fields),
     327                                %get field
     328                                field=md1.(model_fields{i});
     329                                fieldsize=size(field);
     330                                if isobject(field), %recursive call
     331                                        object_fields=fields(md1.(model_fields{i}));
     332                                        for j=1:length(object_fields),
     333                                                %get field
     334                                                field=md1.(model_fields{i}).(object_fields{j});
     335                                                fieldsize=size(field);
     336                                                %size = number of nodes * n
     337                                                if fieldsize(1)==numberofvertices1
     338                                                        md2.(model_fields{i}).(object_fields{j})=field(pos_node,:);
     339                                                elseif (fieldsize(1)==numberofvertices1+1)
     340                                                        md2.(model_fields{i}).(object_fields{j})=[field(pos_node,:); field(end,:)];
     341                                                %size = number of elements * n
     342                                                elseif fieldsize(1)==numberofelements1
     343                                                        md2.(model_fields{i}).(object_fields{j})=field(pos_elem,:);
     344                                                end
     345                                        end
     346                                else
     347                                        %size = number of nodes * n
     348                                        if fieldsize(1)==numberofvertices1
     349                                                md2.(model_fields{i})=field(pos_node,:);
     350                                        elseif (fieldsize(1)==numberofvertices1+1)
     351                                                md2.(model_fields{i})=[field(pos_node,:); field(end,:)];
     352                                        %size = number of elements * n
     353                                        elseif fieldsize(1)==numberofelements1
     354                                                md2.(model_fields{i})=field(pos_elem,:);
     355                                        end
     356                                end
     357                        end
     358
     359                        %modify some specific fields
     360
     361                        %Mesh
     362                        md2.mesh.numberofelements=numberofelements2;
     363                        md2.mesh.numberofvertices=numberofvertices2;
     364                        md2.mesh.elements=elements_2;
     365
     366                        %mesh.uppervertex mesh.lowervertex
     367                        if md1.mesh.dimension==3
     368                                md2.mesh.uppervertex=md1.mesh.uppervertex(pos_node);
     369                                pos=find(~isnan(md2.mesh.uppervertex));
     370                                md2.mesh.uppervertex(pos)=Pnode(md2.mesh.uppervertex(pos));
     371
     372                                md2.mesh.lowervertex=md1.mesh.lowervertex(pos_node);
     373                                pos=find(~isnan(md2.mesh.lowervertex));
     374                                md2.mesh.lowervertex(pos)=Pnode(md2.mesh.lowervertex(pos));
     375
     376                                md2.mesh.upperelements=md1.mesh.upperelements(pos_elem);
     377                                pos=find(~isnan(md2.mesh.upperelements));
     378                                md2.mesh.upperelements(pos)=Pelem(md2.mesh.upperelements(pos));
     379
     380                                md2.mesh.lowerelements=md1.mesh.lowerelements(pos_elem);
     381                                pos=find(~isnan(md2.mesh.lowerelements));
     382                                md2.mesh.lowerelements(pos)=Pelem(md2.mesh.lowerelements(pos));
     383                        end
     384
     385                        %Initial 2d mesh
     386                        if md1.mesh.dimension==3
     387                                flag_elem_2d=flag_elem(1:md1.mesh.numberofelements2d);
     388                                pos_elem_2d=find(flag_elem_2d);
     389                                flag_node_2d=flag_node(1:md1.mesh.numberofvertices2d);
     390                                pos_node_2d=find(flag_node_2d);
     391
     392                                md2.mesh.numberofelements2d=length(pos_elem_2d);
     393                                md2.mesh.numberofvertices2d=length(pos_node_2d);
     394                                md2.mesh.elements2d=md1.mesh.elements2d(pos_elem_2d,:);
     395                                md2.mesh.elements2d(:,1)=Pnode(md2.mesh.elements2d(:,1));
     396                                md2.mesh.elements2d(:,2)=Pnode(md2.mesh.elements2d(:,2));
     397                                md2.mesh.elements2d(:,3)=Pnode(md2.mesh.elements2d(:,3));
     398
     399                                md2.mesh.x2d=md1.mesh.x(pos_node_2d);
     400                                md2.mesh.y2d=md1.mesh.y(pos_node_2d);
     401                        end
     402
     403                        %Edges
     404                        if size(md2.mesh.edges,2)>1, %do not use ~isnan because there are some NaNs...
     405                                %renumber first two columns
     406                                pos=find(md2.mesh.edges(:,4)~=-1);
     407                                md2.mesh.edges(:  ,1)=Pnode(md2.mesh.edges(:,1));
     408                                md2.mesh.edges(:  ,2)=Pnode(md2.mesh.edges(:,2));
     409                                md2.mesh.edges(:  ,3)=Pelem(md2.mesh.edges(:,3));
     410                                md2.mesh.edges(pos,4)=Pelem(md2.mesh.edges(pos,4));
     411                                %remove edges when the 2 vertices are not in the domain.
     412                                md2.mesh.edges=md2.mesh.edges(find(md2.mesh.edges(:,1) & md2.mesh.edges(:,2)),:);
     413                                %Replace all zeros by -1 in the last two columns
     414                                pos=find(md2.mesh.edges(:,3)==0);
     415                                md2.mesh.edges(pos,3)=-1;
     416                                pos=find(md2.mesh.edges(:,4)==0);
     417                                md2.mesh.edges(pos,4)=-1;
     418                                %Invert -1 on the third column with last column (Also invert first two columns!!)
     419                                pos=find(md2.mesh.edges(:,3)==-1);
     420                                md2.mesh.edges(pos,3)=md2.mesh.edges(pos,4);
     421                                md2.mesh.edges(pos,4)=-1;
     422                                values=md2.mesh.edges(pos,2);
     423                                md2.mesh.edges(pos,2)=md2.mesh.edges(pos,1);
     424                                md2.mesh.edges(pos,1)=values;
     425                                %Finally remove edges that do not belong to any element
     426                                pos=find(md2.mesh.edges(:,3)==-1 & md2.mesh.edges(:,4)==-1);
     427                                md2.mesh.edges(pos,:)=[];
     428                        end
     429
     430                        %Penalties
     431                        if ~isnan(md2.diagnostic.vertex_pairing),
     432                                for i=1:size(md1.diagnostic.vertex_pairing,1);
     433                                        md2.diagnostic.vertex_pairing(i,:)=Pnode(md1.diagnostic.vertex_pairing(i,:));
     434                                end
     435                                md2.diagnostic.vertex_pairing=md2.diagnostic.vertex_pairing(find(md2.diagnostic.vertex_pairing(:,1)),:);
     436                        end
     437                        if ~isnan(md2.prognostic.vertex_pairing),
     438                                for i=1:size(md1.prognostic.vertex_pairing,1);
     439                                        md2.prognostic.vertex_pairing(i,:)=Pnode(md1.prognostic.vertex_pairing(i,:));
     440                                end
     441                                md2.prognostic.vertex_pairing=md2.prognostic.vertex_pairing(find(md2.prognostic.vertex_pairing(:,1)),:);
     442                        end
     443
     444                        %recreate segments
     445                        if md1.mesh.dimension==2
     446                                md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices);
     447                                md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity);
     448                                md2.mesh.segments=contourenvelope(md2);
     449                                md2.mesh.vertexonboundary=zeros(numberofvertices2,1); md2.mesh.vertexonboundary(md2.mesh.segments(:,1:2))=1;
     450                        else
     451                                %First do the connectivity for the contourenvelope in 2d
     452                                md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements2d,md2.mesh.numberofvertices2d);
     453                                md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements2d,md2.mesh.vertexconnectivity);
     454                                md2.mesh.segments=contourenvelope(md2);
     455                                md2.mesh.vertexonboundary=zeros(numberofvertices2/md2.mesh.numberoflayers,1); md2.mesh.vertexonboundary(md2.mesh.segments(:,1:2))=1;
     456                                md2.mesh.vertexonboundary=repmat(md2.mesh.vertexonboundary,md2.mesh.numberoflayers,1);
     457                                %Then do it for 3d as usual
     458                                md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices);
     459                                md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity);
     460                        end
     461
     462                        %Boundary conditions: Dirichlets on new boundary
     463                        %Catch the elements that have not been extracted
     464                        orphans_elem=find(~flag_elem);
     465                        orphans_node=unique(md1.mesh.elements(orphans_elem,:))';
     466                        %Figure out which node are on the boundary between md2 and md1
     467                        nodestoflag1=intersect(orphans_node,pos_node);
     468                        nodestoflag2=Pnode(nodestoflag1);
     469                        if numel(md1.diagnostic.spcvx)>1 & numel(md1.diagnostic.spcvy)>2 & numel(md1.diagnostic.spcvz)>2,
     470                                if numel(md1.inversion.vx_obs)>1 & numel(md1.inversion.vy_obs)>1
     471                                        md2.diagnostic.spcvx(nodestoflag2)=md2.inversion.vx_obs(nodestoflag2);
     472                                        md2.diagnostic.spcvy(nodestoflag2)=md2.inversion.vy_obs(nodestoflag2);
     473                                else
     474                                        md2.diagnostic.spcvx(nodestoflag2)=NaN;
     475                                        md2.diagnostic.spcvy(nodestoflag2)=NaN;
     476                                        disp(' ')
     477                                        disp('!! extract warning: spc values should be checked !!')
     478                                        disp(' ')
     479                                end
     480                                %put 0 for vz
     481                                md2.diagnostic.spcvz(nodestoflag2)=0;
     482                        end
     483                        if ~isnan(md1.thermal.spctemperature),
     484                                md2.thermal.spctemperature(nodestoflag2,1)=1;
     485                        end
     486
     487                        %Diagnostic
     488                        if ~isnan(md2.diagnostic.icefront)
     489                                md2.diagnostic.icefront(:,1)=Pnode(md1.diagnostic.icefront(:,1));
     490                                md2.diagnostic.icefront(:,2)=Pnode(md1.diagnostic.icefront(:,2));
     491                                md2.diagnostic.icefront(:,end-1)=Pelem(md1.diagnostic.icefront(:,end-1));
     492                                if md1.mesh.dimension==3
     493                                        md2.diagnostic.icefront(:,3)=Pnode(md1.diagnostic.icefront(:,3));
     494                                        md2.diagnostic.icefront(:,4)=Pnode(md1.diagnostic.icefront(:,4));
     495                                end
     496                                md2.diagnostic.icefront=md2.diagnostic.icefront(find(md2.diagnostic.icefront(:,1) & md2.diagnostic.icefront(:,2) & md2.diagnostic.icefront(:,end)),:);
     497                        end
     498
     499                        %Results fields
     500                        if isstruct(md1.results),
     501                                md2.results=struct();
     502                                solutionfields=fields(md1.results);
     503                                for i=1:length(solutionfields),
     504                                        %get subfields
     505                                        solutionsubfields=fields(md1.results.(solutionfields{i}));
     506                                        for j=1:length(solutionsubfields),
     507                                                field=md1.results.(solutionfields{i}).(solutionsubfields{j});
     508                                                if length(field)==numberofvertices1,
     509                                                        md2.results.(solutionfields{i}).(solutionsubfields{j})=field(pos_node);
     510                                                elseif length(field)==numberofelements1,
     511                                                        md2.results.(solutionfields{i}).(solutionsubfields{j})=field(pos_elem);
     512                                                else
     513                                                        md2.results.(solutionfields{i}).(solutionsubfields{j})=field;
     514                                                end
     515                                        end
     516                                end
     517                        end
     518
     519                        %Keep track of pos_node and pos_elem
     520                        md2.mesh.extractedvertices=pos_node;
     521                        md2.mesh.extractedelements=pos_elem;
     522                end % }}}
     523                function md = extrude(md,varargin) % {{{
     524                        %EXTRUDE - vertically extrude a 2d mesh
     525                        %
     526                        %   vertically extrude a 2d mesh and create corresponding 3d mesh.
     527                        %   The vertical distribution can:
     528                        %    - follow a polynomial law
     529                        %    - follow two polynomial laws, one for the lower part and one for the upper part of the mesh
     530                        %    - be discribed by a list of coefficients (between 0 and 1)
     531                        %   
     532                        %
     533                        %   Usage:
     534                        %      md=extrude(md,numlayers,extrusionexponent);
     535                        %      md=extrude(md,numlayers,lowerexponent,upperexponent);
     536                        %      md=extrude(md,listofcoefficients);
     537                        %
     538                        %   Example:
     539                        %      md=extrude(md,8,3);
     540                        %      md=extrude(md,8,3,2);
     541                        %      md=extrude(md,[0 0.2 0.5 0.7 0.9 0.95 1]);
     542                        %
     543                        %   See also: MODELEXTRACT, COLLAPSE
     544
     545                        %some checks on list of arguments
     546                        if ((nargin>4) | (nargin<2) | (nargout~=1)),
     547                                help extrude;
     548                                error('extrude error message');
     549                        end
     550
     551                        %Extrude the mesh
     552                        if nargin==2, %list of coefficients
     553                                clist=varargin{1};
     554                                if any(clist<0) | any(clist>1),
     555                                        error('extrusioncoefficients must be between 0 and 1');
     556                                end
     557                                extrusionlist=sort(unique([clist(:);0;1]));
     558                                numlayers=length(extrusionlist);
     559                        elseif nargin==3, %one polynomial law
     560                                if varargin{2}<=0,
     561                                        help extrude;
     562                                        error('extrusionexponent must be >=0');
     563                                end
     564                                numlayers=varargin{1};
     565                                extrusionlist=((0:1:numlayers-1)/(numlayers-1)).^varargin{2};
     566                        elseif nargin==4, %two polynomial laws
     567                                numlayers=varargin{1};
     568                                lowerexp=varargin{2};
     569                                upperexp=varargin{3};
     570
     571                                if varargin{2}<=0 | varargin{3}<=0,
     572                                        help extrude;
     573                                        error('lower and upper extrusionexponents must be >=0');
     574                                end
     575
     576                                lowerextrusionlist=[(0:2/(numlayers-1):1).^lowerexp]/2;
     577                                upperextrusionlist=[(0:2/(numlayers-1):1).^upperexp]/2;
     578                                extrusionlist=sort(unique([lowerextrusionlist 1-upperextrusionlist]));
     579
     580                        end
     581
     582                        if numlayers<2,
     583                                error('number of layers should be at least 2');
     584                        end
     585                        if md.mesh.dimension==3,
     586                                error('Cannot extrude a 3d mesh (extrude cannot be called more than once)');
     587                        end
     588
     589                        %Initialize with the 2d mesh
     590                        x3d=[];
     591                        y3d=[];
     592                        z3d=[];  %the lower node is on the bed
     593                        thickness3d=md.geometry.thickness; %thickness and bed for these nodes
     594                        bed3d=md.geometry.bed;
     595
     596                        %Create the new layers
     597                        for i=1:numlayers,
     598                                x3d=[x3d; md.mesh.x];
     599                                y3d=[y3d; md.mesh.y];
     600                                %nodes are distributed between bed and surface accordingly to the given exponent
     601                                z3d=[z3d; bed3d+thickness3d*extrusionlist(i)];
     602                        end
     603                        number_nodes3d=size(x3d,1); %number of 3d nodes for the non extruded part of the mesh
     604
     605                        %Extrude elements
     606                        elements3d=[];
     607                        for i=1:numlayers-1,
     608                                elements3d=[elements3d;[md.mesh.elements+(i-1)*md.mesh.numberofvertices md.mesh.elements+i*md.mesh.numberofvertices]]; %Create the elements of the 3d mesh for the non extruded part
     609                        end
     610                        number_el3d=size(elements3d,1); %number of 3d nodes for the non extruded part of the mesh
     611
     612                        %Keep a trace of lower and upper nodes
     613                        mesh.lowervertex=NaN*ones(number_nodes3d,1);
     614                        mesh.uppervertex=NaN*ones(number_nodes3d,1);
     615                        mesh.lowervertex(md.mesh.numberofvertices+1:end)=1:(numlayers-1)*md.mesh.numberofvertices;
     616                        mesh.uppervertex(1:(numlayers-1)*md.mesh.numberofvertices)=md.mesh.numberofvertices+1:number_nodes3d;
     617                        md.mesh.lowervertex=mesh.lowervertex;
     618                        md.mesh.uppervertex=mesh.uppervertex;
     619
     620                        %same for lower and upper elements
     621                        mesh.lowerelements=NaN*ones(number_el3d,1);
     622                        mesh.upperelements=NaN*ones(number_el3d,1);
     623                        mesh.lowerelements(md.mesh.numberofelements+1:end)=1:(numlayers-2)*md.mesh.numberofelements;
     624                        mesh.upperelements(1:(numlayers-2)*md.mesh.numberofelements)=md.mesh.numberofelements+1:(numlayers-1)*md.mesh.numberofelements;
     625                        md.mesh.lowerelements=mesh.lowerelements;
     626                        md.mesh.upperelements=mesh.upperelements;
     627
     628                        %Save old mesh
     629                        md.mesh.x2d=md.mesh.x;
     630                        md.mesh.y2d=md.mesh.y;
     631                        md.mesh.elements2d=md.mesh.elements;
     632                        md.mesh.numberofelements2d=md.mesh.numberofelements;
     633                        md.mesh.numberofvertices2d=md.mesh.numberofvertices;
     634
     635                        %Update mesh type
     636                        md.mesh.dimension=3;
     637
     638                        %Build global 3d mesh
     639                        md.mesh.elements=elements3d;
     640                        md.mesh.x=x3d;
     641                        md.mesh.y=y3d;
     642                        md.mesh.z=z3d;
     643                        md.mesh.numberofelements=number_el3d;
     644                        md.mesh.numberofvertices=number_nodes3d;
     645                        md.mesh.numberoflayers=numlayers;
     646
     647                        %Ok, now deal with the other fields from the 2d mesh:
     648
     649                        %lat long
     650                        md.mesh.lat=project3d(md,'vector',md.mesh.lat,'type','node');
     651                        md.mesh.long=project3d(md,'vector',md.mesh.long,'type','node');
     652
     653                        %drag coefficient is limited to nodes that are on the bedrock.
     654                        md.friction.coefficient=project3d(md,'vector',md.friction.coefficient,'type','node','layer',1);
     655
     656                        %p and q (same deal, except for element that are on the bedrock: )
     657                        md.friction.p=project3d(md,'vector',md.friction.p,'type','element');
     658                        md.friction.q=project3d(md,'vector',md.friction.q,'type','element');
     659
     660                        %observations
     661                        md.inversion.vx_obs=project3d(md,'vector',md.inversion.vx_obs,'type','node');
     662                        md.inversion.vy_obs=project3d(md,'vector',md.inversion.vy_obs,'type','node');
     663                        md.inversion.vel_obs=project3d(md,'vector',md.inversion.vel_obs,'type','node');
     664                        md.surfaceforcings.mass_balance=project3d(md,'vector',md.surfaceforcings.mass_balance,'type','node');
     665                        md.surfaceforcings.precipitation=project3d(md,'vector',md.surfaceforcings.precipitation,'type','node');
     666                        md.balancethickness.thickening_rate=project3d(md,'vector',md.balancethickness.thickening_rate,'type','node');
     667                        md.surfaceforcings.monthlytemperatures=project3d(md,'vector',md.surfaceforcings.monthlytemperatures,'type','node');
     668
     669                        %results
     670                        if ~isnan(md.initialization.vx),md.initialization.vx=project3d(md,'vector',md.initialization.vx,'type','node');end;
     671                        if ~isnan(md.initialization.vy),md.initialization.vy=project3d(md,'vector',md.initialization.vy,'type','node');end;
     672                        if ~isnan(md.initialization.vz),md.initialization.vz=project3d(md,'vector',md.initialization.vz,'type','node');end;
     673                        if ~isnan(md.initialization.vel),md.initialization.vel=project3d(md,'vector',md.initialization.vel,'type','node');end;
     674                        if ~isnan(md.initialization.temperature),md.initialization.temperature=project3d(md,'vector',md.initialization.temperature,'type','node');end;
     675                        if ~isnan(md.initialization.waterfraction),md.initialization.waterfraction=project3d(md,'vector',md.initialization.waterfraction,'type','node');end;
     676
     677                        %bedinfo and surface info
     678                        md.mesh.elementonbed=project3d(md,'vector',ones(md.mesh.numberofelements2d,1),'type','element','layer',1);
     679                        md.mesh.elementonsurface=project3d(md,'vector',ones(md.mesh.numberofelements2d,1),'type','element','layer',md.mesh.numberoflayers-1);
     680                        md.mesh.vertexonbed=project3d(md,'vector',ones(md.mesh.numberofvertices2d,1),'type','node','layer',1);
     681                        md.mesh.vertexonsurface=project3d(md,'vector',ones(md.mesh.numberofvertices2d,1),'type','node','layer',md.mesh.numberoflayers);
     682
     683                        %elementstype
     684                        if ~isnan(md.flowequation.element_equation)
     685                                oldelements_type=md.flowequation.element_equation;
     686                                md.flowequation.element_equation=zeros(number_el3d,1);
     687                                md.flowequation.element_equation=project3d(md,'vector',oldelements_type,'type','element');
     688                        end
     689
     690                        %verticestype
     691                        if ~isnan(md.flowequation.vertex_equation)
     692                                oldvertices_type=md.flowequation.vertex_equation;
     693                                md.flowequation.vertex_equation=zeros(number_nodes3d,1);
     694                                md.flowequation.vertex_equation=project3d(md,'vector',oldvertices_type,'type','node');
     695                        end
     696                        md.flowequation.bordermacayeal=project3d(md,'vector',md.flowequation.bordermacayeal,'type','node');
     697                        md.flowequation.borderpattyn=project3d(md,'vector',md.flowequation.borderpattyn,'type','node');
     698                        md.flowequation.borderstokes=project3d(md,'vector',md.flowequation.borderstokes,'type','node');
     699
     700                        %boundary conditions
     701                        md.diagnostic.spcvx=project3d(md,'vector',md.diagnostic.spcvx,'type','node');
     702                        md.diagnostic.spcvy=project3d(md,'vector',md.diagnostic.spcvy,'type','node');
     703                        md.diagnostic.spcvz=project3d(md,'vector',md.diagnostic.spcvz,'type','node');
     704                        md.thermal.spctemperature=project3d(md,'vector',md.thermal.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',NaN);
     705                        md.prognostic.spcthickness=project3d(md,'vector',md.prognostic.spcthickness,'type','node');
     706                        md.balancethickness.spcthickness=project3d(md,'vector',md.balancethickness.spcthickness,'type','node');
     707                        md.diagnostic.referential=project3d(md,'vector',md.diagnostic.referential,'type','node');
     708
     709                        %in 3d, pressureload: [node1 node2 node3 node4 element]
     710                        pressureload_layer1=[md.diagnostic.icefront(:,1:2)  md.diagnostic.icefront(:,2)+md.mesh.numberofvertices2d  md.diagnostic.icefront(:,1)+md.mesh.numberofvertices2d  md.diagnostic.icefront(:,3:4)]; %Add two columns on the first layer
     711                        pressureload=[];
     712                        for i=1:numlayers-1,
     713                                pressureload=[pressureload ;pressureload_layer1(:,1:4)+(i-1)*md.mesh.numberofvertices2d pressureload_layer1(:,5)+(i-1)*md.mesh.numberofelements2d pressureload_layer1(:,6)];
     714                        end
     715                        md.diagnostic.icefront=pressureload;
     716
     717                        %connectivity
     718                        md.mesh.elementconnectivity=repmat(md.mesh.elementconnectivity,numlayers-1,1);
     719                        md.mesh.elementconnectivity(find(md.mesh.elementconnectivity==0))=NaN;
     720                        for i=2:numlayers-1,
     721                                md.mesh.elementconnectivity((i-1)*md.mesh.numberofelements2d+1:(i)*md.mesh.numberofelements2d,:)...
     722                                        =md.mesh.elementconnectivity((i-1)*md.mesh.numberofelements2d+1:(i)*md.mesh.numberofelements2d,:)+md.mesh.numberofelements2d;
     723                        end
     724                        md.mesh.elementconnectivity(find(isnan(md.mesh.elementconnectivity)))=0;
     725
     726                        %materials
     727                        md.materials.rheology_B=project3d(md,'vector',md.materials.rheology_B,'type','node');
     728                        md.materials.rheology_n=project3d(md,'vector',md.materials.rheology_n,'type','element');
     729                        if isa(md.materials,'matdamageice')
     730                                md.materials.rheology_Z=project3d(md,'vector',md.materials.rheology_Z,'type','node');
     731                        end
     732
     733                        %parameters
     734                        md.geometry.surface=project3d(md,'vector',md.geometry.surface,'type','node');
     735                        md.geometry.thickness=project3d(md,'vector',md.geometry.thickness,'type','node');
     736                        md.geometry.hydrostatic_ratio=project3d(md,'vector',md.geometry.hydrostatic_ratio,'type','node');
     737                        md.geometry.bed=project3d(md,'vector',md.geometry.bed,'type','node');
     738                        md.geometry.bathymetry=project3d(md,'vector',md.geometry.bathymetry,'type','node');
     739                        md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node');
     740                        md.mask.elementonfloatingice=project3d(md,'vector',md.mask.elementonfloatingice,'type','element');
     741                        md.mask.vertexonfloatingice=project3d(md,'vector',md.mask.vertexonfloatingice,'type','node');
     742                        md.mask.elementongroundedice=project3d(md,'vector',md.mask.elementongroundedice,'type','element');
     743                        md.mask.vertexongroundedice=project3d(md,'vector',md.mask.vertexongroundedice,'type','node');
     744                        md.mask.elementonwater=project3d(md,'vector',md.mask.elementonwater,'type','element');
     745                        md.mask.vertexonwater=project3d(md,'vector',md.mask.vertexonwater,'type','node');
     746                        if ~isnan(md.inversion.cost_functions_coefficients),md.inversion.cost_functions_coefficients=project3d(md,'vector',md.inversion.cost_functions_coefficients,'type','node');end;
     747                        if ~isnan(md.inversion.min_parameters),md.inversion.min_parameters=project3d(md,'vector',md.inversion.min_parameters,'type','node');end;
     748                        if ~isnan(md.inversion.max_parameters),md.inversion.max_parameters=project3d(md,'vector',md.inversion.max_parameters,'type','node');end;
     749                        if ~isnan(md.qmu.partition),md.qmu.partition=project3d(md,'vector',md.qmu.partition','type','node');end
     750                        if(md.surfaceforcings.isdelta18o),md.surfaceforcings.temperatures_lgm=project3d(md,'vector',md.surfaceforcings.temperatures_lgm,'type','node');end
     751                        if(md.surfaceforcings.isdelta18o),md.surfaceforcings.temperatures_presentday=project3d(md,'vector',md.surfaceforcings.temperatures_presentday,'type','node');end
     752                        if(md.surfaceforcings.isdelta18o),md.surfaceforcings.precipitations_presentday=project3d(md,'vector',md.surfaceforcings.precipitations_presentday,'type','node');end
     753
     754                        %Put lithostatic pressure if there is an existing pressure
     755                        if ~isnan(md.initialization.pressure),
     756                                md.initialization.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z);
     757                        end
     758
     759                        %special for thermal modeling:
     760                        md.basalforcings.melting_rate=project3d(md,'vector',md.basalforcings.melting_rate,'type','node','layer',1);
     761                        if ~isnan(md.basalforcings.geothermalflux)
     762                                md.basalforcings.geothermalflux=project3d(md,'vector',md.basalforcings.geothermalflux,'type','node','layer',1); %bedrock only gets geothermal flux
     763                        end
     764
     765                        %increase connectivity if less than 25:
     766                        if md.mesh.average_vertex_connectivity<=25,
     767                                md.mesh.average_vertex_connectivity=100;
     768                        end
    772769                        end % }}}
    773                  function md = structtomodel(md,structmd) % {{{
    774 
    775                          if ~isstruct(structmd) error('input model is not a structure'); end
    776 
    777                          %loaded model is a struct, initialize output and recover all fields
    778                          md = structtoobj(model,structmd);
    779 
    780                          %Old field now classes
    781                          if (isfield(structmd,'timestepping') & isnumeric(md.timestepping)), md.timestepping=timestepping(); end
    782                          if (isfield(structmd,'mask') & isnumeric(md.mask)),md.mask=mask(); end
    783 
    784                          %Field name change
    785                          if isfield(structmd,'drag'), md.friction.coefficient=structmd.drag; end
    786                          if isfield(structmd,'p'), md.friction.p=structmd.p; end
    787                          if isfield(structmd,'q'), md.friction.q=structmd.p; end
    788                          if isfield(structmd,'melting'), md.basalforcings.melting_rate=structmd.melting; end
    789                          if isfield(structmd,'melting_rate'), md.basalforcings.melting_rate=structmd.melting_rate; end
    790                          if isfield(structmd,'accumulation'), md.surfaceforcings.mass_balance=structmd.accumulation; end
    791                          if isfield(structmd,'numberofgrids'), md.mesh.numberofvertices=structmd.numberofgrids; end
    792                          if isfield(structmd,'numberofgrids2d'), md.mesh.numberofvertices2d=structmd.numberofgrids2d; end
    793                          if isfield(structmd,'uppergrids'), md.mesh.uppervertex=structmd.uppergrids; end
    794                          if isfield(structmd,'lowergrids'), md.mesh.lowervertex=structmd.lowergrids; end
    795                          if isfield(structmd,'gridonbed'), md.mesh.vertexonbed=structmd.gridonbed; end
    796                          if isfield(structmd,'gridonsurface'), md.mesh.vertexonsurface=structmd.gridonsurface; end
    797                          if isfield(structmd,'extractedgrids'), md.mesh.extractedvertices=structmd.extractedgrids; end
    798                          if isfield(structmd,'gridoniceshelf'), md.mask.vertexonfloatingice=structmd.gridoniceshelf; end
    799                          if isfield(structmd,'gridonicesheet'), md.mask.vertexongroundedice=structmd.gridonicesheet; end
    800                          if isfield(structmd,'gridonwater'), md.mask.vertexonwater=structmd.gridonwater; end
    801                          if isfield(structmd,'gridonboundary'), md.mesh.vertexonboundary=structmd.gridonboundary; end
    802                          if isfield(structmd,'petscoptions') & ~isempty(structmd.petscoptions), md.solver=structmd.petscoptions; end
    803                          if isfield(structmd,'g'), md.constants.g=structmd.g; end
    804                          if isfield(structmd,'yts'), md.constants.yts=structmd.yts; end
    805                          if isfield(structmd,'surface_mass_balance'), md.surfaceforcings.mass_balance=structmd.surface_mass_balance; end
    806                          if isfield(structmd,'basal_melting_rate'), md.basalforcings.melting_rate=structmd.basal_melting_rate; end
    807                          if isfield(structmd,'basal_melting_rate_correction'), md.basalforcings.melting_rate_correction=structmd.basal_melting_rate_correction; end
    808                          if isfield(structmd,'geothermalflux'), md.basalforcings.geothermalflux=structmd.geothermalflux; end
    809                          if isfield(structmd,'drag'), md.friction.coefficient=structmd.drag; end
    810                          if isfield(structmd,'drag_coefficient'), md.friction.coefficient=structmd.drag_coefficient; end
    811                          if isfield(structmd,'drag_p'), md.friction.p=structmd.drag_p; end
    812                          if isfield(structmd,'drag_q'), md.friction.q=structmd.drag_q; end
    813                          if isfield(structmd,'riftproperties'), %old implementation
    814                                  md.rifts=rifts();
    815                                  md.rifts.riftproperties=structmd.riftproperties;
    816                                  md.rifts.riftstruct=structmd.rifts;
    817                                  md.rifts.riftproperties=structmd.riftinfo;
    818                          end
    819                          if isfield(structmd,'bamg'), md.private.bamg=structmd.bamg; end
    820                          if isfield(structmd,'lowmem'), md.settings.lowmem=structmd.lowmem; end
    821                          if isfield(structmd,'io_gather'), md.settings.io_gather=structmd.io_gather; end
    822                          if isfield(structmd,'spcwatercolumn'), md.hydrology.spcwatercolumn=structmd.spcwatercolumn; end
    823                          if isfield(structmd,'hydro_n'), md.hydrology.n=structmd.hydro_n; end
    824                          if isfield(structmd,'hydro_p'), md.hydrology.p=structmd.hydro_p; end
    825                          if isfield(structmd,'hydro_q'), md.hydrology.q=structmd.hydro_q; end
    826                          if isfield(structmd,'hydro_CR'), md.hydrology.CR=structmd.hydro_CR; end
    827                          if isfield(structmd,'hydro_kn'), md.hydrology.kn=structmd.hydro_kn; end
    828                          if isfield(structmd,'spctemperature'), md.thermal.spctemperature=structmd.spctemperature; end
    829                          if isfield(structmd,'min_thermal_constraints'), md.thermal.penalty_threshold=structmd.min_thermal_constraints; end
    830                          if isfield(structmd,'artificial_diffusivity'), md.thermal.stabilization=structmd.artificial_diffusivity; end
    831                          if isfield(structmd,'max_nonlinear_iterations'), md.thermal.maxiter=structmd.max_nonlinear_iterations; end
    832                          if isfield(structmd,'stabilize_constraints'), md.thermal.penalty_lock=structmd.stabilize_constraints; end
    833                          if isfield(structmd,'penalty_offset'), md.thermal.penalty_factor=structmd.penalty_offset; end
    834                          if isfield(structmd,'name'), md.miscellaneous.name=structmd.name; end
    835                          if isfield(structmd,'notes'), md.miscellaneous.notes=structmd.notes; end
    836                          if isfield(structmd,'dummy'), md.miscellaneous.dummy=structmd.dummy; end
    837                          if isfield(structmd,'dt'), md.timestepping.time_step=structmd.dt; end
    838                          if isfield(structmd,'ndt'), md.timestepping.final_time=structmd.ndt; end
    839                          if isfield(structmd,'time_adapt'), md.timestepping.time_adapt=structmd.time_adapt; end
    840                          if isfield(structmd,'cfl_coefficient'), md.timestepping.cfl_coefficient=structmd.cfl_coefficient; end
    841                          if isfield(structmd,'spcthickness'), md.prognostic.spcthickness=structmd.spcthickness; end
    842                          if isfield(structmd,'artificial_diffusivity'), md.prognostic.stabilization=structmd.artificial_diffusivity; end
    843                          if isfield(structmd,'hydrostatic_adjustment'), md.prognostic.hydrostatic_adjustment=structmd.hydrostatic_adjustment; end
    844                          if isfield(structmd,'penalties'), md.prognostic.vertex_pairing=structmd.penalties; end
    845                          if isfield(structmd,'penalty_offset'), md.prognostic.penalty_factor=structmd.penalty_offset; end
    846                          if isfield(structmd,'B'), md.materials.rheology_B=structmd.B; end
    847                          if isfield(structmd,'n'), md.materials.rheology_n=structmd.n; end
    848                          if isfield(structmd,'rheology_B'), md.materials.rheology_B=structmd.rheology_B; end
    849                          if isfield(structmd,'rheology_n'), md.materials.rheology_n=structmd.rheology_n; end
    850                          if isfield(structmd,'elementoniceshelf'), md.mask.elementonfloatingice=structmd.elementoniceshelf; end
    851                          if isfield(structmd,'elementonicesheet'), md.mask.elementongroundedice=structmd.elementonicesheet; end
    852                          if isfield(structmd,'elementonwater'), md.mask.elementonwater=structmd.elementonwater; end
    853                          if isfield(structmd,'nodeoniceshelf'), md.mask.vertexonfloatingice=structmd.nodeoniceshelf; end
    854                          if isfield(structmd,'nodeonicesheet'), md.mask.vertexongroundedice=structmd.nodeonicesheet; end
    855                          if isfield(structmd,'nodeonwater'), md.mask.vertexonwater=structmd.nodeonwater; end
    856                          if isfield(structmd,'spcthickness'), md.balancethickness.spcthickness=structmd.spcthickness; end
    857                          if isfield(structmd,'artificial_diffusivity'), md.balancethickness.stabilization=structmd.artificial_diffusivity; end
    858                          if isfield(structmd,'dhdt'), md.balancethickness.thickening_rate=structmd.dhdt; end
    859                          if isfield(structmd,'ismacayealpattyn'), md.flowequation.ismacayealpattyn=structmd.ismacayealpattyn; end
    860                          if isfield(structmd,'ishutter'), md.flowequation.ishutter=structmd.ishutter; end
    861                          if isfield(structmd,'isstokes'), md.flowequation.isstokes=structmd.isstokes; end
    862                          if isfield(structmd,'elements_type'), md.flowequation.element_equation=structmd.elements_type; end
    863                          if isfield(structmd,'vertices_type'), md.flowequation.vertex_equation=structmd.vertices_type; end
    864                          if isfield(structmd,'eps_rel'), md.steadystate.reltol=structmd.eps_rel; end
    865                          if isfield(structmd,'max_steadystate_iterations'), md.steadystate.maxiter=structmd.max_steadystate_iterations; end
    866                          if isfield(structmd,'isdiagnostic'), md.transient.isdiagnostic=structmd.isdiagnostic; end
    867                          if isfield(structmd,'isprognostic'), md.transient.isprognostic=structmd.isprognostic; end
    868                          if isfield(structmd,'isthermal'), md.transient.isthermal=structmd.isthermal; end
    869                          if isfield(structmd,'control_analysis'), md.inversion.iscontrol=structmd.control_analysis; end
    870                          if isfield(structmd,'weights'), md.inversion.cost_functions_coefficients=structmd.weights; end
    871                          if isfield(structmd,'nsteps'), md.inversion.nsteps=structmd.nsteps; end
    872                          if isfield(structmd,'maxiter_per_step'), md.inversion.maxiter_per_step=structmd.maxiter_per_step; end
    873                          if isfield(structmd,'cm_min'), md.inversion.min_parameters=structmd.cm_min; end
    874                          if isfield(structmd,'cm_max'), md.inversion.max_parameters=structmd.cm_max; end
    875                          if isfield(structmd,'vx_obs'), md.inversion.vx_obs=structmd.vx_obs; end
    876                          if isfield(structmd,'vy_obs'), md.inversion.vy_obs=structmd.vy_obs; end
    877                          if isfield(structmd,'vel_obs'), md.inversion.vel_obs=structmd.vel_obs; end
    878                          if isfield(structmd,'thickness_obs'), md.inversion.thickness_obs=structmd.thickness_obs; end
    879                          if isfield(structmd,'vx'), md.initialization.vx=structmd.vx; end
    880                          if isfield(structmd,'vy'), md.initialization.vy=structmd.vy; end
    881                          if isfield(structmd,'vz'), md.initialization.vz=structmd.vz; end
    882                          if isfield(structmd,'vel'), md.initialization.vel=structmd.vel; end
    883                          if isfield(structmd,'pressure'), md.initialization.pressure=structmd.pressure; end
    884                          if isfield(structmd,'temperature'), md.initialization.temperature=structmd.temperature; end
    885                          if isfield(structmd,'waterfraction'), md.initialization.waterfraction=structmd.waterfraction; end
    886                          if isfield(structmd,'watercolumn'), md.initialization.watercolumn=structmd.watercolumn; end
    887                          if isfield(structmd,'surface'), md.geometry.surface=structmd.surface; end
    888                          if isfield(structmd,'bed'), md.geometry.bed=structmd.bed; end
    889                          if isfield(structmd,'thickness'), md.geometry.thickness=structmd.thickness; end
    890                          if isfield(structmd,'bathymetry'), md.geometry.bathymetry=structmd.bathymetry; end
    891                          if isfield(structmd,'thickness_coeff'), md.geometry.hydrostatic_ratio=structmd.thickness_coeff; end
    892                          if isfield(structmd,'connectivity'), md.mesh.average_vertex_connectivity=structmd.connectivity; end
    893                          if isfield(structmd,'extractednodes'), md.mesh.extractedvertices=structmd.extractednodes; end
    894                          if isfield(structmd,'extractedelements'), md.mesh.extractedelements=structmd.extractedelements; end
    895                          if isfield(structmd,'nodeonboundary'), md.mesh.vertexonboundary=structmd.nodeonboundary; end
    896                          if isfield(structmd,'hemisphere'), md.mesh.hemisphere=structmd.hemisphere; end
    897                          if isfield(structmd,'lat'), md.mesh.lat=structmd.lat; end
    898                          if isfield(structmd,'long'), md.mesh.long=structmd.long; end
    899                          if isfield(structmd,'segments'), md.mesh.segments=structmd.segments; end
    900                          if isfield(structmd,'segmentmarkers'), md.mesh.segmentmarkers=structmd.segmentmarkers; end
    901                          if isfield(structmd,'dim'), md.mesh.dimension=structmd.dim; end
    902                          if isfield(structmd,'numlayers'), md.mesh.numberoflayers=structmd.numlayers; end
    903                          if isfield(structmd,'numberofelements'), md.mesh.numberofelements=structmd.numberofelements; end
    904                          if isfield(structmd,'numberofvertices'), md.mesh.numberofvertices=structmd.numberofvertices; end
    905                          if isfield(structmd,'numberofnodes'), md.mesh.numberofvertices=structmd.numberofnodes; end
    906                          if isfield(structmd,'numberofedges'), md.mesh.numberofedges=structmd.numberofedges; end
    907                          if isfield(structmd,'numberofelements2d'), md.mesh.numberofelements2d=structmd.numberofelements2d; end
    908                          if isfield(structmd,'numberofnodes2d'), md.mesh.numberofvertices2d=structmd.numberofnodes2d; end
    909                          if isfield(structmd,'nodeconnectivity'), md.mesh.vertexconnectivity=structmd.nodeconnectivity; end
    910                          if isfield(structmd,'elementconnectivity'), md.mesh.elementconnectivity=structmd.elementconnectivity; end
    911                          if isfield(structmd,'uppernodes'), md.mesh.uppervertex=structmd.uppernodes; end
    912                          if isfield(structmd,'lowernodes'), md.mesh.lowervertex=structmd.lowernodes; end
    913                          if isfield(structmd,'upperelements'), md.mesh.upperelements=structmd.upperelements; end
    914                          if isfield(structmd,'lowerelements'), md.mesh.lowerelements=structmd.lowerelements; end
    915                          if isfield(structmd,'elementonbed'), md.mesh.elementonbed=structmd.elementonbed; end
    916                          if isfield(structmd,'elementonsurface'), md.mesh.elementonsurface=structmd.elementonsurface; end
    917                          if isfield(structmd,'nodeonsurface'), md.mesh.vertexonsurface=structmd.nodeonsurface; end
    918                          if isfield(structmd,'nodeonbed'), md.mesh.vertexonbed=structmd.nodeonbed; end
    919                          if isfield(structmd,'elements2d'), md.mesh.elements2d=structmd.elements2d; end
    920                          if isfield(structmd,'y2d'), md.mesh.y2d=structmd.y2d; end
    921                          if isfield(structmd,'x2d'), md.mesh.x2d=structmd.x2d; end
    922                          if isfield(structmd,'elements'), md.mesh.elements=structmd.elements; end
    923                          if isfield(structmd,'edges'), md.mesh.edges=structmd.edges; end
    924                          if isfield(structmd,'y'), md.mesh.y=structmd.y; end
    925                          if isfield(structmd,'x'), md.mesh.x=structmd.x; end
    926                          if isfield(structmd,'z'), md.mesh.z=structmd.z; end
    927                          if isfield(structmd,'mask'), md.flaim.criterion=structmd.mask; end
    928                          if isfield(structmd,'pressureload'), md.diagnostic.icefront=structmd.pressureload; end
    929                          if isfield(structmd,'diagnostic_ref'), md.diagnostic.referential=structmd.diagnostic_ref; end
    930                          if isfield(structmd,'npart'); md.qmu.numberofpartitions=structmd.npart; end
    931                          if isfield(structmd,'part'); md.qmu.partition=structmd.part; end
    932                                  
    933                          %Field changes
    934                          if (isfield(structmd,'type') & ischar(structmd.type)),
    935                                  if strcmpi(structmd.type,'2d'), md.mesh.dimension=2; end
    936                                  if strcmpi(structmd.type,'3d'), md.mesh.dimension=3; end
    937                          end
    938                          if isnumeric(md.verbose),
    939                                  md.verbose=verbose;
    940                          end
    941                          if size(md.diagnostic.icefront,2)==3 || size(md.diagnostic.icefront,2)==5,
    942                                  front=md.diagnostic.icefront;
    943                                  md.diagnostic.icefront=[front 1*md.mask.elementonfloatingice(front(:,end))];
    944                          end
    945                          if isfield(structmd,'spcvelocity'),
    946                                  md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
    947                                  md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
    948                                  md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
    949                                  pos=find(structmd.spcvelocity(:,1)); md.diagnostic.spcvx(pos)=structmd.spcvelocity(pos,4);
    950                                  pos=find(structmd.spcvelocity(:,2)); md.diagnostic.spcvy(pos)=structmd.spcvelocity(pos,5);
    951                                  pos=find(structmd.spcvelocity(:,3)); md.diagnostic.spcvz(pos)=structmd.spcvelocity(pos,6);
    952                          end
    953                          if isfield(structmd,'spcvx'),
    954                                  md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
    955                                  pos=find(~isnan(structmd.spcvx)); md.diagnostic.spcvx(pos)=structmd.spcvx(pos);
    956                          end
    957                          if isfield(structmd,'spcvy'),
    958                                  md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
    959                                  pos=find(~isnan(structmd.spcvy)); md.diagnostic.spcvy(pos)=structmd.spcvy(pos);     
    960                          end
    961                          if isfield(structmd,'spcvz'),
    962                                  md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
    963                                  pos=find(~isnan(structmd.spcvz)); md.diagnostic.spcvz(pos)=structmd.spcvz(pos);     
    964                          end
    965                          if ~isempty(structmd.pressureload) & ismember(structmd.pressureload(end,end),[118 119 120]),
    966                                  pos=find(structmd.pressureload(:,end)==120); md.diagnostic.icefront(pos,end)=0;
    967                                  pos=find(structmd.pressureload(:,end)==118); md.diagnostic.icefront(pos,end)=1;
    968                                  pos=find(structmd.pressureload(:,end)==119); md.diagnostic.icefront(pos,end)=2;
    969                          end
    970                          if isfield(structmd,'elements_type') & structmd.elements_type(end,end)>50,
    971                                  pos=find(structmd.elements_type==59); md.flowequation.element_equation(pos,end)=0;
    972                                  pos=find(structmd.elements_type==55); md.flowequation.element_equation(pos,end)=1;
    973                                  pos=find(structmd.elements_type==56); md.flowequation.element_equation(pos,end)=2;
    974                                  pos=find(structmd.elements_type==60); md.flowequation.element_equation(pos,end)=3;
    975                                  pos=find(structmd.elements_type==62); md.flowequation.element_equation(pos,end)=4;
    976                                  pos=find(structmd.elements_type==57); md.flowequation.element_equation(pos,end)=5;
    977                                  pos=find(structmd.elements_type==58); md.flowequation.element_equation(pos,end)=6;
    978                                  pos=find(structmd.elements_type==61); md.flowequation.element_equation(pos,end)=7;
    979                          end
    980                          if isfield(structmd,'vertices_type') & structmd.vertices_type(end,end)>50,
    981                                  pos=find(structmd.vertices_type==59); md.flowequation.vertex_equation(pos,end)=0;
    982                                  pos=find(structmd.vertices_type==55); md.flowequation.vertex_equation(pos,end)=1;
    983                                  pos=find(structmd.vertices_type==56); md.flowequation.vertex_equation(pos,end)=2;
    984                                  pos=find(structmd.vertices_type==60); md.flowequation.vertex_equation(pos,end)=3;
    985                                  pos=find(structmd.vertices_type==62); md.flowequation.vertex_equation(pos,end)=4;
    986                                  pos=find(structmd.vertices_type==57); md.flowequation.vertex_equation(pos,end)=5;
    987                                  pos=find(structmd.vertices_type==58); md.flowequation.vertex_equation(pos,end)=6;
    988                                  pos=find(structmd.vertices_type==61); md.flowequation.vertex_equation(pos,end)=7;
    989                          end
    990                          if isfield(structmd,'rheology_law') & isnumeric(structmd.rheology_law),
    991                                  if (structmd.rheology_law==272), md.materials.rheology_law='None';      end
    992                                  if (structmd.rheology_law==368), md.materials.rheology_law='Paterson';  end
    993                                  if (structmd.rheology_law==369), md.materials.rheology_law='Arrhenius'; end
    994                          end
    995                          if isfield(structmd,'groundingline_migration') & isnumeric(structmd.groundingline_migration),
    996                                  if (structmd.groundingline_migration==272), md.groundingline.migration='None';      end
    997                                  if (structmd.groundingline_migration==273), md.groundingline.migration='AgressiveMigration';  end
    998                                  if (structmd.groundingline_migration==274), md.groundingline.migration='SoftMigration'; end
    999                          end
    1000                          if isfield(structmd,'control_type') & isnumeric(structmd.control_type),
    1001                                  if (structmd.control_type==143), md.inversion.control_parameters={'FrictionCoefficient'}; end
    1002                                  if (structmd.control_type==190), md.inversion.control_parameters={'RheologyBbar'}; end
    1003                                  if (structmd.control_type==147), md.inversion.control_parameters={'Thickeningrate'}; end
    1004                          end
    1005                          if isfield(structmd,'cm_responses') & ismember(structmd.cm_responses(end,end),[165:170 383 388 389]),
    1006                                  pos=find(structmd.cm_responses==166); md.inversion.cost_functions(pos)=101;
    1007                                  pos=find(structmd.cm_responses==167); md.inversion.cost_functions(pos)=102;
    1008                                  pos=find(structmd.cm_responses==168); md.inversion.cost_functions(pos)=103;
    1009                                  pos=find(structmd.cm_responses==169); md.inversion.cost_functions(pos)=104;
    1010                                  pos=find(structmd.cm_responses==170); md.inversion.cost_functions(pos)=105;
    1011                                  pos=find(structmd.cm_responses==165); md.inversion.cost_functions(pos)=201;
    1012                                  pos=find(structmd.cm_responses==389); md.inversion.cost_functions(pos)=501;
    1013                                  pos=find(structmd.cm_responses==388); md.inversion.cost_functions(pos)=502;
    1014                                  pos=find(structmd.cm_responses==382); md.inversion.cost_functions(pos)=503;
    1015                          end
    1016 
    1017                          if isfield(structmd,'artificial_diffusivity') & structmd.artificial_diffusivity==2,
    1018                                          md.thermal.stabilization=2;
    1019                                          md.prognostic.stabilization=1;
    1020                                          md.balancethickness.stabilization=1;
    1021                          end
    1022                          if isnumeric(md.prognostic.hydrostatic_adjustment)
    1023                                  if md.prognostic.hydrostatic_adjustment==269,
    1024                                          md.prognostic.hydrostatic_adjustment='Incremental';
    1025                                  else
    1026                                          md.prognostic.hydrostatic_adjustment='Absolute';
    1027                                  end
    1028                          end
    1029 
    1030                          %New fields
    1031                          if ~isfield(structmd,'upperelements');
    1032                                  md.mesh.upperelements=transpose(1:md.mesh.numberofelements)+md.mesh.numberofelements2d;
    1033                                  md.mesh.upperelements(end-md.mesh.numberofelements2d+1:end)=NaN;
    1034                          end
    1035                          if ~isfield(structmd,'lowerelements');
    1036                                  md.mesh.lowerelements=transpose(1:md.mesh.numberofelements)-md.mesh.numberofelements2d;
    1037                                  md.mesh.lowerelements(1:md.mesh.numberofelements2d)=NaN;
    1038                          end
    1039                                  
    1040                          if ~isfield(structmd,'diagnostic_ref');
    1041                                  md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
    1042                          end
    1043 
    1044                  end% }}}
    1045                  function md = setdefaultparameters(md) % {{{
    1046 
    1047                          %initialize subclasses
    1048                          md.mesh             = mesh();
    1049                          md.mask             = mask();
    1050                          md.constants        = constants();
    1051                          md.geometry         = geometry();
    1052                          md.initialization   = initialization();
    1053                          md.surfaceforcings  = surfaceforcings();
    1054                          md.basalforcings    = basalforcings();
    1055                          md.friction         = friction();
    1056                          md.rifts            = rifts();
    1057                          md.timestepping     = timestepping();
    1058                          md.groundingline    = groundingline();
    1059                          md.materials        = matice();
    1060                          md.flowequation     = flowequation();
    1061                          md.debug            = debug();
    1062                          md.verbose          = verbose('solution',true,'qmu',true,'control',true);
    1063                          md.settings         = settings();
    1064                          md.solver           = solver();
    1065                          if ismumps(),
    1066                                  md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum(),mumpsoptions());
    1067                          else
    1068                                  md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum(),iluasmoptions());
    1069                          end
    1070                          md.cluster          = generic();
    1071                          md.balancethickness = balancethickness();
    1072                          md.diagnostic       = diagnostic();
    1073                          md.hydrology        = hydrology();
    1074                          md.prognostic       = prognostic();
    1075                          md.thermal          = thermal();
    1076                          md.steadystate      = steadystate();
    1077                          md.transient        = transient();
    1078                          md.autodiff         = autodiff();
    1079                          md.flaim            = flaim();
    1080                          md.inversion        = inversion();
    1081                          md.qmu              = qmu();
    1082                          md.radaroverlay     = radaroverlay();
    1083                          md.results          = struct();
    1084                          md.miscellaneous    = miscellaneous();
    1085                          md.private          = private();
    1086                  end
    1087                  %}}}
    1088                  function disp(obj) % {{{
    1089                          disp(sprintf('%19s: %-22s -- %s','mesh'            ,['[1x1 ' class(obj.mesh) ']'],'mesh properties'));
    1090                          disp(sprintf('%19s: %-22s -- %s','mask'            ,['[1x1 ' class(obj.mask) ']'],'defines grounded and floating elements'));
    1091                          disp(sprintf('%19s: %-22s -- %s','geometry'        ,['[1x1 ' class(obj.geometry) ']'],'surface elevation, bedrock topography, ice thickness,...'));
    1092                          disp(sprintf('%19s: %-22s -- %s','constants'       ,['[1x1 ' class(obj.constants) ']'],'physical constants'));
    1093                          disp(sprintf('%19s: %-22s -- %s','surfaceforcings' ,['[1x1 ' class(obj.surfaceforcings) ']'],'surface forcings'));
    1094                          disp(sprintf('%19s: %-22s -- %s','basalforcings'   ,['[1x1 ' class(obj.basalforcings) ']'],'bed forcings'));
    1095                          disp(sprintf('%19s: %-22s -- %s','materials'       ,['[1x1 ' class(obj.materials) ']'],'material properties'));
    1096                          disp(sprintf('%19s: %-22s -- %s','friction'        ,['[1x1 ' class(obj.friction) ']'],'basal friction/drag properties'));
    1097                          disp(sprintf('%19s: %-22s -- %s','flowequation'    ,['[1x1 ' class(obj.flowequation) ']'],'flow equations'));
    1098                          disp(sprintf('%19s: %-22s -- %s','timestepping'    ,['[1x1 ' class(obj.timestepping) ']'],'time stepping for transient models'));
    1099                          disp(sprintf('%19s: %-22s -- %s','initialization'  ,['[1x1 ' class(obj.initialization) ']'],'initial guess/state'));
    1100                          disp(sprintf('%19s: %-22s -- %s','rifts'           ,['[1x1 ' class(obj.rifts) ']'],'rifts properties'));
    1101                          disp(sprintf('%19s: %-22s -- %s','debug'           ,['[1x1 ' class(obj.debug) ']'],'debugging tools (valgrind, gprof)'));
    1102                          disp(sprintf('%19s: %-22s -- %s','verbose'         ,['[1x1 ' class(obj.verbose) ']'],'verbosity level in solve'));
    1103                          disp(sprintf('%19s: %-22s -- %s','settings'        ,['[1x1 ' class(obj.settings) ']'],'settings properties'));
    1104                          disp(sprintf('%19s: %-22s -- %s','solver'          ,['[1x1 ' class(obj.solver) ']'],'PETSc options for each solution'));
    1105                          disp(sprintf('%19s: %-22s -- %s','cluster'         ,['[1x1 ' class(obj.cluster) ']'],'cluster parameters (number of cpus...)'));
    1106                          disp(sprintf('%19s: %-22s -- %s','balancethickness',['[1x1 ' class(obj.balancethickness) ']'],'parameters for balancethickness solution'));
    1107                          disp(sprintf('%19s: %-22s -- %s','diagnostic'      ,['[1x1 ' class(obj.diagnostic) ']'],'parameters for diagnostic solution'));
    1108                          disp(sprintf('%19s: %-22s -- %s','groundingline'   ,['[1x1 ' class(obj.groundingline) ']'],'parameters for groundingline solution'));
    1109                          disp(sprintf('%19s: %-22s -- %s','hydrology'       ,['[1x1 ' class(obj.hydrology) ']'],'parameters for hydrology solution'));
    1110                          disp(sprintf('%19s: %-22s -- %s','prognostic'      ,['[1x1 ' class(obj.prognostic) ']'],'parameters for prognostic solution'));
    1111                          disp(sprintf('%19s: %-22s -- %s','thermal'         ,['[1x1 ' class(obj.thermal) ']'],'parameters for thermal solution'));
    1112                          disp(sprintf('%19s: %-22s -- %s','steadystate'     ,['[1x1 ' class(obj.steadystate) ']'],'parameters for steadystate solution'));
    1113                          disp(sprintf('%19s: %-22s -- %s','transient'       ,['[1x1 ' class(obj.transient) ']'],'parameters for transient solution'));
    1114                          disp(sprintf('%19s: %-22s -- %s','autodiff'        ,['[1x1 ' class(obj.autodiff) ']'],'automatic differentiation parameters'));
    1115                          disp(sprintf('%19s: %-22s -- %s','flaim'           ,['[1x1 ' class(obj.flaim) ']'],'flaim parameters'));
    1116                          disp(sprintf('%19s: %-22s -- %s','inversion'       ,['[1x1 ' class(obj.inversion) ']'],'parameters for inverse methods'));
    1117                          disp(sprintf('%19s: %-22s -- %s','qmu'             ,['[1x1 ' class(obj.qmu) ']'],'dakota properties'));
    1118                          disp(sprintf('%19s: %-22s -- %s','results'         ,['[1x1 ' class(obj.results) ']'],'model results'));
    1119                          disp(sprintf('%19s: %-22s -- %s','radaroverlay'    ,['[1x1 ' class(obj.radaroverlay) ']'],'radar image for plot overlay'));
    1120                          disp(sprintf('%19s: %-22s -- %s','miscellaneous'   ,['[1x1 ' class(obj.miscellaneous) ']'],'miscellaneous fields'));
    1121                  end % }}}
    1122          end
     770                function md = structtomodel(md,structmd) % {{{
     771
     772                        if ~isstruct(structmd) error('input model is not a structure'); end
     773
     774                        %loaded model is a struct, initialize output and recover all fields
     775                        md = structtoobj(model,structmd);
     776
     777                        %Old field now classes
     778                        if (isfield(structmd,'timestepping') & isnumeric(md.timestepping)), md.timestepping=timestepping(); end
     779                        if (isfield(structmd,'mask') & isnumeric(md.mask)),md.mask=mask(); end
     780
     781                        %Field name change
     782                        if isfield(structmd,'drag'), md.friction.coefficient=structmd.drag; end
     783                        if isfield(structmd,'p'), md.friction.p=structmd.p; end
     784                        if isfield(structmd,'q'), md.friction.q=structmd.p; end
     785                        if isfield(structmd,'melting'), md.basalforcings.melting_rate=structmd.melting; end
     786                        if isfield(structmd,'melting_rate'), md.basalforcings.melting_rate=structmd.melting_rate; end
     787                        if isfield(structmd,'accumulation'), md.surfaceforcings.mass_balance=structmd.accumulation; end
     788                        if isfield(structmd,'numberofgrids'), md.mesh.numberofvertices=structmd.numberofgrids; end
     789                        if isfield(structmd,'numberofgrids2d'), md.mesh.numberofvertices2d=structmd.numberofgrids2d; end
     790                        if isfield(structmd,'uppergrids'), md.mesh.uppervertex=structmd.uppergrids; end
     791                        if isfield(structmd,'lowergrids'), md.mesh.lowervertex=structmd.lowergrids; end
     792                        if isfield(structmd,'gridonbed'), md.mesh.vertexonbed=structmd.gridonbed; end
     793                        if isfield(structmd,'gridonsurface'), md.mesh.vertexonsurface=structmd.gridonsurface; end
     794                        if isfield(structmd,'extractedgrids'), md.mesh.extractedvertices=structmd.extractedgrids; end
     795                        if isfield(structmd,'gridoniceshelf'), md.mask.vertexonfloatingice=structmd.gridoniceshelf; end
     796                        if isfield(structmd,'gridonicesheet'), md.mask.vertexongroundedice=structmd.gridonicesheet; end
     797                        if isfield(structmd,'gridonwater'), md.mask.vertexonwater=structmd.gridonwater; end
     798                        if isfield(structmd,'gridonboundary'), md.mesh.vertexonboundary=structmd.gridonboundary; end
     799                        if isfield(structmd,'petscoptions') & ~isempty(structmd.petscoptions), md.solver=structmd.petscoptions; end
     800                        if isfield(structmd,'g'), md.constants.g=structmd.g; end
     801                        if isfield(structmd,'yts'), md.constants.yts=structmd.yts; end
     802                        if isfield(structmd,'surface_mass_balance'), md.surfaceforcings.mass_balance=structmd.surface_mass_balance; end
     803                        if isfield(structmd,'basal_melting_rate'), md.basalforcings.melting_rate=structmd.basal_melting_rate; end
     804                        if isfield(structmd,'basal_melting_rate_correction'), md.basalforcings.melting_rate_correction=structmd.basal_melting_rate_correction; end
     805                        if isfield(structmd,'geothermalflux'), md.basalforcings.geothermalflux=structmd.geothermalflux; end
     806                        if isfield(structmd,'drag'), md.friction.coefficient=structmd.drag; end
     807                        if isfield(structmd,'drag_coefficient'), md.friction.coefficient=structmd.drag_coefficient; end
     808                        if isfield(structmd,'drag_p'), md.friction.p=structmd.drag_p; end
     809                        if isfield(structmd,'drag_q'), md.friction.q=structmd.drag_q; end
     810                        if isfield(structmd,'riftproperties'), %old implementation
     811                                md.rifts=rifts();
     812                                md.rifts.riftproperties=structmd.riftproperties;
     813                                md.rifts.riftstruct=structmd.rifts;
     814                                md.rifts.riftproperties=structmd.riftinfo;
     815                        end
     816                        if isfield(structmd,'bamg'), md.private.bamg=structmd.bamg; end
     817                        if isfield(structmd,'lowmem'), md.settings.lowmem=structmd.lowmem; end
     818                        if isfield(structmd,'io_gather'), md.settings.io_gather=structmd.io_gather; end
     819                        if isfield(structmd,'spcwatercolumn'), md.hydrology.spcwatercolumn=structmd.spcwatercolumn; end
     820                        if isfield(structmd,'hydro_n'), md.hydrology.n=structmd.hydro_n; end
     821                        if isfield(structmd,'hydro_p'), md.hydrology.p=structmd.hydro_p; end
     822                        if isfield(structmd,'hydro_q'), md.hydrology.q=structmd.hydro_q; end
     823                        if isfield(structmd,'hydro_CR'), md.hydrology.CR=structmd.hydro_CR; end
     824                        if isfield(structmd,'hydro_kn'), md.hydrology.kn=structmd.hydro_kn; end
     825                        if isfield(structmd,'spctemperature'), md.thermal.spctemperature=structmd.spctemperature; end
     826                        if isfield(structmd,'min_thermal_constraints'), md.thermal.penalty_threshold=structmd.min_thermal_constraints; end
     827                        if isfield(structmd,'artificial_diffusivity'), md.thermal.stabilization=structmd.artificial_diffusivity; end
     828                        if isfield(structmd,'max_nonlinear_iterations'), md.thermal.maxiter=structmd.max_nonlinear_iterations; end
     829                        if isfield(structmd,'stabilize_constraints'), md.thermal.penalty_lock=structmd.stabilize_constraints; end
     830                        if isfield(structmd,'penalty_offset'), md.thermal.penalty_factor=structmd.penalty_offset; end
     831                        if isfield(structmd,'name'), md.miscellaneous.name=structmd.name; end
     832                        if isfield(structmd,'notes'), md.miscellaneous.notes=structmd.notes; end
     833                        if isfield(structmd,'dummy'), md.miscellaneous.dummy=structmd.dummy; end
     834                        if isfield(structmd,'dt'), md.timestepping.time_step=structmd.dt; end
     835                        if isfield(structmd,'ndt'), md.timestepping.final_time=structmd.ndt; end
     836                        if isfield(structmd,'time_adapt'), md.timestepping.time_adapt=structmd.time_adapt; end
     837                        if isfield(structmd,'cfl_coefficient'), md.timestepping.cfl_coefficient=structmd.cfl_coefficient; end
     838                        if isfield(structmd,'spcthickness'), md.prognostic.spcthickness=structmd.spcthickness; end
     839                        if isfield(structmd,'artificial_diffusivity'), md.prognostic.stabilization=structmd.artificial_diffusivity; end
     840                        if isfield(structmd,'hydrostatic_adjustment'), md.prognostic.hydrostatic_adjustment=structmd.hydrostatic_adjustment; end
     841                        if isfield(structmd,'penalties'), md.prognostic.vertex_pairing=structmd.penalties; end
     842                        if isfield(structmd,'penalty_offset'), md.prognostic.penalty_factor=structmd.penalty_offset; end
     843                        if isfield(structmd,'B'), md.materials.rheology_B=structmd.B; end
     844                        if isfield(structmd,'n'), md.materials.rheology_n=structmd.n; end
     845                        if isfield(structmd,'rheology_B'), md.materials.rheology_B=structmd.rheology_B; end
     846                        if isfield(structmd,'rheology_n'), md.materials.rheology_n=structmd.rheology_n; end
     847                        if isfield(structmd,'elementoniceshelf'), md.mask.elementonfloatingice=structmd.elementoniceshelf; end
     848                        if isfield(structmd,'elementonicesheet'), md.mask.elementongroundedice=structmd.elementonicesheet; end
     849                        if isfield(structmd,'elementonwater'), md.mask.elementonwater=structmd.elementonwater; end
     850                        if isfield(structmd,'nodeoniceshelf'), md.mask.vertexonfloatingice=structmd.nodeoniceshelf; end
     851                        if isfield(structmd,'nodeonicesheet'), md.mask.vertexongroundedice=structmd.nodeonicesheet; end
     852                        if isfield(structmd,'nodeonwater'), md.mask.vertexonwater=structmd.nodeonwater; end
     853                        if isfield(structmd,'spcthickness'), md.balancethickness.spcthickness=structmd.spcthickness; end
     854                        if isfield(structmd,'artificial_diffusivity'), md.balancethickness.stabilization=structmd.artificial_diffusivity; end
     855                        if isfield(structmd,'dhdt'), md.balancethickness.thickening_rate=structmd.dhdt; end
     856                        if isfield(structmd,'ismacayealpattyn'), md.flowequation.ismacayealpattyn=structmd.ismacayealpattyn; end
     857                        if isfield(structmd,'ishutter'), md.flowequation.ishutter=structmd.ishutter; end
     858                        if isfield(structmd,'isstokes'), md.flowequation.isstokes=structmd.isstokes; end
     859                        if isfield(structmd,'elements_type'), md.flowequation.element_equation=structmd.elements_type; end
     860                        if isfield(structmd,'vertices_type'), md.flowequation.vertex_equation=structmd.vertices_type; end
     861                        if isfield(structmd,'eps_rel'), md.steadystate.reltol=structmd.eps_rel; end
     862                        if isfield(structmd,'max_steadystate_iterations'), md.steadystate.maxiter=structmd.max_steadystate_iterations; end
     863                        if isfield(structmd,'isdiagnostic'), md.transient.isdiagnostic=structmd.isdiagnostic; end
     864                        if isfield(structmd,'isprognostic'), md.transient.isprognostic=structmd.isprognostic; end
     865                        if isfield(structmd,'isthermal'), md.transient.isthermal=structmd.isthermal; end
     866                        if isfield(structmd,'control_analysis'), md.inversion.iscontrol=structmd.control_analysis; end
     867                        if isfield(structmd,'weights'), md.inversion.cost_functions_coefficients=structmd.weights; end
     868                        if isfield(structmd,'nsteps'), md.inversion.nsteps=structmd.nsteps; end
     869                        if isfield(structmd,'maxiter_per_step'), md.inversion.maxiter_per_step=structmd.maxiter_per_step; end
     870                        if isfield(structmd,'cm_min'), md.inversion.min_parameters=structmd.cm_min; end
     871                        if isfield(structmd,'cm_max'), md.inversion.max_parameters=structmd.cm_max; end
     872                        if isfield(structmd,'vx_obs'), md.inversion.vx_obs=structmd.vx_obs; end
     873                        if isfield(structmd,'vy_obs'), md.inversion.vy_obs=structmd.vy_obs; end
     874                        if isfield(structmd,'vel_obs'), md.inversion.vel_obs=structmd.vel_obs; end
     875                        if isfield(structmd,'thickness_obs'), md.inversion.thickness_obs=structmd.thickness_obs; end
     876                        if isfield(structmd,'vx'), md.initialization.vx=structmd.vx; end
     877                        if isfield(structmd,'vy'), md.initialization.vy=structmd.vy; end
     878                        if isfield(structmd,'vz'), md.initialization.vz=structmd.vz; end
     879                        if isfield(structmd,'vel'), md.initialization.vel=structmd.vel; end
     880                        if isfield(structmd,'pressure'), md.initialization.pressure=structmd.pressure; end
     881                        if isfield(structmd,'temperature'), md.initialization.temperature=structmd.temperature; end
     882                        if isfield(structmd,'waterfraction'), md.initialization.waterfraction=structmd.waterfraction; end
     883                        if isfield(structmd,'watercolumn'), md.initialization.watercolumn=structmd.watercolumn; end
     884                        if isfield(structmd,'surface'), md.geometry.surface=structmd.surface; end
     885                        if isfield(structmd,'bed'), md.geometry.bed=structmd.bed; end
     886                        if isfield(structmd,'thickness'), md.geometry.thickness=structmd.thickness; end
     887                        if isfield(structmd,'bathymetry'), md.geometry.bathymetry=structmd.bathymetry; end
     888                        if isfield(structmd,'thickness_coeff'), md.geometry.hydrostatic_ratio=structmd.thickness_coeff; end
     889                        if isfield(structmd,'connectivity'), md.mesh.average_vertex_connectivity=structmd.connectivity; end
     890                        if isfield(structmd,'extractednodes'), md.mesh.extractedvertices=structmd.extractednodes; end
     891                        if isfield(structmd,'extractedelements'), md.mesh.extractedelements=structmd.extractedelements; end
     892                        if isfield(structmd,'nodeonboundary'), md.mesh.vertexonboundary=structmd.nodeonboundary; end
     893                        if isfield(structmd,'hemisphere'), md.mesh.hemisphere=structmd.hemisphere; end
     894                        if isfield(structmd,'lat'), md.mesh.lat=structmd.lat; end
     895                        if isfield(structmd,'long'), md.mesh.long=structmd.long; end
     896                        if isfield(structmd,'segments'), md.mesh.segments=structmd.segments; end
     897                        if isfield(structmd,'segmentmarkers'), md.mesh.segmentmarkers=structmd.segmentmarkers; end
     898                        if isfield(structmd,'dim'), md.mesh.dimension=structmd.dim; end
     899                        if isfield(structmd,'numlayers'), md.mesh.numberoflayers=structmd.numlayers; end
     900                        if isfield(structmd,'numberofelements'), md.mesh.numberofelements=structmd.numberofelements; end
     901                        if isfield(structmd,'numberofvertices'), md.mesh.numberofvertices=structmd.numberofvertices; end
     902                        if isfield(structmd,'numberofnodes'), md.mesh.numberofvertices=structmd.numberofnodes; end
     903                        if isfield(structmd,'numberofedges'), md.mesh.numberofedges=structmd.numberofedges; end
     904                        if isfield(structmd,'numberofelements2d'), md.mesh.numberofelements2d=structmd.numberofelements2d; end
     905                        if isfield(structmd,'numberofnodes2d'), md.mesh.numberofvertices2d=structmd.numberofnodes2d; end
     906                        if isfield(structmd,'nodeconnectivity'), md.mesh.vertexconnectivity=structmd.nodeconnectivity; end
     907                        if isfield(structmd,'elementconnectivity'), md.mesh.elementconnectivity=structmd.elementconnectivity; end
     908                        if isfield(structmd,'uppernodes'), md.mesh.uppervertex=structmd.uppernodes; end
     909                        if isfield(structmd,'lowernodes'), md.mesh.lowervertex=structmd.lowernodes; end
     910                        if isfield(structmd,'upperelements'), md.mesh.upperelements=structmd.upperelements; end
     911                        if isfield(structmd,'lowerelements'), md.mesh.lowerelements=structmd.lowerelements; end
     912                        if isfield(structmd,'elementonbed'), md.mesh.elementonbed=structmd.elementonbed; end
     913                        if isfield(structmd,'elementonsurface'), md.mesh.elementonsurface=structmd.elementonsurface; end
     914                        if isfield(structmd,'nodeonsurface'), md.mesh.vertexonsurface=structmd.nodeonsurface; end
     915                        if isfield(structmd,'nodeonbed'), md.mesh.vertexonbed=structmd.nodeonbed; end
     916                        if isfield(structmd,'elements2d'), md.mesh.elements2d=structmd.elements2d; end
     917                        if isfield(structmd,'y2d'), md.mesh.y2d=structmd.y2d; end
     918                        if isfield(structmd,'x2d'), md.mesh.x2d=structmd.x2d; end
     919                        if isfield(structmd,'elements'), md.mesh.elements=structmd.elements; end
     920                        if isfield(structmd,'edges'),
     921                                md.mesh.edges=structmd.edges;
     922                                md.mesh.edges(isnan(md.mesh.edges))=-1;
     923                        end
     924                        if isfield(structmd,'y'), md.mesh.y=structmd.y; end
     925                        if isfield(structmd,'x'), md.mesh.x=structmd.x; end
     926                        if isfield(structmd,'z'), md.mesh.z=structmd.z; end
     927                        if isfield(structmd,'mask'), md.flaim.criterion=structmd.mask; end
     928                        if isfield(structmd,'pressureload'), md.diagnostic.icefront=structmd.pressureload; end
     929                        if isfield(structmd,'diagnostic_ref'), md.diagnostic.referential=structmd.diagnostic_ref; end
     930                        if isfield(structmd,'npart'); md.qmu.numberofpartitions=structmd.npart; end
     931                        if isfield(structmd,'part'); md.qmu.partition=structmd.part; end
     932
     933                        %Field changes
     934                        if (isfield(structmd,'type') & ischar(structmd.type)),
     935                                if strcmpi(structmd.type,'2d'), md.mesh.dimension=2; end
     936                                if strcmpi(structmd.type,'3d'), md.mesh.dimension=3; end
     937                        end
     938                        if isnumeric(md.verbose),
     939                                md.verbose=verbose;
     940                        end
     941                        if size(md.diagnostic.icefront,2)==3 || size(md.diagnostic.icefront,2)==5,
     942                                front=md.diagnostic.icefront;
     943                                md.diagnostic.icefront=[front 1*md.mask.elementonfloatingice(front(:,end))];
     944                        end
     945                        if isfield(structmd,'spcvelocity'),
     946                                md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
     947                                md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
     948                                md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
     949                                pos=find(structmd.spcvelocity(:,1)); md.diagnostic.spcvx(pos)=structmd.spcvelocity(pos,4);
     950                                pos=find(structmd.spcvelocity(:,2)); md.diagnostic.spcvy(pos)=structmd.spcvelocity(pos,5);
     951                                pos=find(structmd.spcvelocity(:,3)); md.diagnostic.spcvz(pos)=structmd.spcvelocity(pos,6);
     952                        end
     953                        if isfield(structmd,'spcvx'),
     954                                md.diagnostic.spcvx=NaN*ones(md.mesh.numberofvertices,1);
     955                                pos=find(~isnan(structmd.spcvx)); md.diagnostic.spcvx(pos)=structmd.spcvx(pos);
     956                        end
     957                        if isfield(structmd,'spcvy'),
     958                                md.diagnostic.spcvy=NaN*ones(md.mesh.numberofvertices,1);
     959                                pos=find(~isnan(structmd.spcvy)); md.diagnostic.spcvy(pos)=structmd.spcvy(pos);     
     960                        end
     961                        if isfield(structmd,'spcvz'),
     962                                md.diagnostic.spcvz=NaN*ones(md.mesh.numberofvertices,1);
     963                                pos=find(~isnan(structmd.spcvz)); md.diagnostic.spcvz(pos)=structmd.spcvz(pos);     
     964                        end
     965                        if ~isempty(structmd.pressureload) & ismember(structmd.pressureload(end,end),[118 119 120]),
     966                                pos=find(structmd.pressureload(:,end)==120); md.diagnostic.icefront(pos,end)=0;
     967                                pos=find(structmd.pressureload(:,end)==118); md.diagnostic.icefront(pos,end)=1;
     968                                pos=find(structmd.pressureload(:,end)==119); md.diagnostic.icefront(pos,end)=2;
     969                        end
     970                        if isfield(structmd,'elements_type') & structmd.elements_type(end,end)>50,
     971                                pos=find(structmd.elements_type==59); md.flowequation.element_equation(pos,end)=0;
     972                                pos=find(structmd.elements_type==55); md.flowequation.element_equation(pos,end)=1;
     973                                pos=find(structmd.elements_type==56); md.flowequation.element_equation(pos,end)=2;
     974                                pos=find(structmd.elements_type==60); md.flowequation.element_equation(pos,end)=3;
     975                                pos=find(structmd.elements_type==62); md.flowequation.element_equation(pos,end)=4;
     976                                pos=find(structmd.elements_type==57); md.flowequation.element_equation(pos,end)=5;
     977                                pos=find(structmd.elements_type==58); md.flowequation.element_equation(pos,end)=6;
     978                                pos=find(structmd.elements_type==61); md.flowequation.element_equation(pos,end)=7;
     979                        end
     980                        if isfield(structmd,'vertices_type') & structmd.vertices_type(end,end)>50,
     981                                pos=find(structmd.vertices_type==59); md.flowequation.vertex_equation(pos,end)=0;
     982                                pos=find(structmd.vertices_type==55); md.flowequation.vertex_equation(pos,end)=1;
     983                                pos=find(structmd.vertices_type==56); md.flowequation.vertex_equation(pos,end)=2;
     984                                pos=find(structmd.vertices_type==60); md.flowequation.vertex_equation(pos,end)=3;
     985                                pos=find(structmd.vertices_type==62); md.flowequation.vertex_equation(pos,end)=4;
     986                                pos=find(structmd.vertices_type==57); md.flowequation.vertex_equation(pos,end)=5;
     987                                pos=find(structmd.vertices_type==58); md.flowequation.vertex_equation(pos,end)=6;
     988                                pos=find(structmd.vertices_type==61); md.flowequation.vertex_equation(pos,end)=7;
     989                        end
     990                        if isfield(structmd,'rheology_law') & isnumeric(structmd.rheology_law),
     991                                if (structmd.rheology_law==272), md.materials.rheology_law='None';      end
     992                                if (structmd.rheology_law==368), md.materials.rheology_law='Paterson';  end
     993                                if (structmd.rheology_law==369), md.materials.rheology_law='Arrhenius'; end
     994                        end
     995                        if isfield(structmd,'groundingline_migration') & isnumeric(structmd.groundingline_migration),
     996                                if (structmd.groundingline_migration==272), md.groundingline.migration='None';      end
     997                                if (structmd.groundingline_migration==273), md.groundingline.migration='AgressiveMigration';  end
     998                                if (structmd.groundingline_migration==274), md.groundingline.migration='SoftMigration'; end
     999                        end
     1000                        if isfield(structmd,'control_type') & isnumeric(structmd.control_type),
     1001                                if (structmd.control_type==143), md.inversion.control_parameters={'FrictionCoefficient'}; end
     1002                                if (structmd.control_type==190), md.inversion.control_parameters={'RheologyBbar'}; end
     1003                                if (structmd.control_type==147), md.inversion.control_parameters={'Thickeningrate'}; end
     1004                        end
     1005                        if isfield(structmd,'cm_responses') & ismember(structmd.cm_responses(end,end),[165:170 383 388 389]),
     1006                                pos=find(structmd.cm_responses==166); md.inversion.cost_functions(pos)=101;
     1007                                pos=find(structmd.cm_responses==167); md.inversion.cost_functions(pos)=102;
     1008                                pos=find(structmd.cm_responses==168); md.inversion.cost_functions(pos)=103;
     1009                                pos=find(structmd.cm_responses==169); md.inversion.cost_functions(pos)=104;
     1010                                pos=find(structmd.cm_responses==170); md.inversion.cost_functions(pos)=105;
     1011                                pos=find(structmd.cm_responses==165); md.inversion.cost_functions(pos)=201;
     1012                                pos=find(structmd.cm_responses==389); md.inversion.cost_functions(pos)=501;
     1013                                pos=find(structmd.cm_responses==388); md.inversion.cost_functions(pos)=502;
     1014                                pos=find(structmd.cm_responses==382); md.inversion.cost_functions(pos)=503;
     1015                        end
     1016
     1017                        if isfield(structmd,'artificial_diffusivity') & structmd.artificial_diffusivity==2,
     1018                                        md.thermal.stabilization=2;
     1019                                        md.prognostic.stabilization=1;
     1020                                        md.balancethickness.stabilization=1;
     1021                        end
     1022                        if isnumeric(md.prognostic.hydrostatic_adjustment)
     1023                                if md.prognostic.hydrostatic_adjustment==269,
     1024                                        md.prognostic.hydrostatic_adjustment='Incremental';
     1025                                else
     1026                                        md.prognostic.hydrostatic_adjustment='Absolute';
     1027                                end
     1028                        end
     1029
     1030                        %New fields
     1031                        if ~isfield(structmd,'upperelements');
     1032                                md.mesh.upperelements=transpose(1:md.mesh.numberofelements)+md.mesh.numberofelements2d;
     1033                                md.mesh.upperelements(end-md.mesh.numberofelements2d+1:end)=NaN;
     1034                        end
     1035                        if ~isfield(structmd,'lowerelements');
     1036                                md.mesh.lowerelements=transpose(1:md.mesh.numberofelements)-md.mesh.numberofelements2d;
     1037                                md.mesh.lowerelements(1:md.mesh.numberofelements2d)=NaN;
     1038                        end
     1039
     1040                        if ~isfield(structmd,'diagnostic_ref');
     1041                                md.diagnostic.referential=NaN*ones(md.mesh.numberofvertices,6);
     1042                        end
     1043
     1044                end% }}}
     1045                function md = setdefaultparameters(md) % {{{
     1046
     1047                        %initialize subclasses
     1048                        md.mesh             = mesh();
     1049                        md.mask             = mask();
     1050                        md.constants        = constants();
     1051                        md.geometry         = geometry();
     1052                        md.initialization   = initialization();
     1053                        md.surfaceforcings  = surfaceforcings();
     1054                        md.basalforcings    = basalforcings();
     1055                        md.friction         = friction();
     1056                        md.rifts            = rifts();
     1057                        md.timestepping     = timestepping();
     1058                        md.groundingline    = groundingline();
     1059                        md.materials        = matice();
     1060                        md.flowequation     = flowequation();
     1061                        md.debug            = debug();
     1062                        md.verbose          = verbose('solution',true,'qmu',true,'control',true);
     1063                        md.settings         = settings();
     1064                        md.solver           = solver();
     1065                        if ismumps(),
     1066                                md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum(),mumpsoptions());
     1067                        else
     1068                                md.solver           = addoptions(md.solver,DiagnosticVertAnalysisEnum(),iluasmoptions());
     1069                        end
     1070                        md.cluster          = generic();
     1071                        md.balancethickness = balancethickness();
     1072                        md.diagnostic       = diagnostic();
     1073                        md.hydrology        = hydrology();
     1074                        md.prognostic       = prognostic();
     1075                        md.thermal          = thermal();
     1076                        md.steadystate      = steadystate();
     1077                        md.transient        = transient();
     1078                        md.autodiff         = autodiff();
     1079                        md.flaim            = flaim();
     1080                        md.inversion        = inversion();
     1081                        md.qmu              = qmu();
     1082                        md.radaroverlay     = radaroverlay();
     1083                        md.results          = struct();
     1084                        md.miscellaneous    = miscellaneous();
     1085                        md.private          = private();
     1086                end
     1087                %}}}
     1088                function disp(obj) % {{{
     1089                        disp(sprintf('%19s: %-22s -- %s','mesh'            ,['[1x1 ' class(obj.mesh) ']'],'mesh properties'));
     1090                        disp(sprintf('%19s: %-22s -- %s','mask'            ,['[1x1 ' class(obj.mask) ']'],'defines grounded and floating elements'));
     1091                        disp(sprintf('%19s: %-22s -- %s','geometry'        ,['[1x1 ' class(obj.geometry) ']'],'surface elevation, bedrock topography, ice thickness,...'));
     1092                        disp(sprintf('%19s: %-22s -- %s','constants'       ,['[1x1 ' class(obj.constants) ']'],'physical constants'));
     1093                        disp(sprintf('%19s: %-22s -- %s','surfaceforcings' ,['[1x1 ' class(obj.surfaceforcings) ']'],'surface forcings'));
     1094                        disp(sprintf('%19s: %-22s -- %s','basalforcings'   ,['[1x1 ' class(obj.basalforcings) ']'],'bed forcings'));
     1095                        disp(sprintf('%19s: %-22s -- %s','materials'       ,['[1x1 ' class(obj.materials) ']'],'material properties'));
     1096                        disp(sprintf('%19s: %-22s -- %s','friction'        ,['[1x1 ' class(obj.friction) ']'],'basal friction/drag properties'));
     1097                        disp(sprintf('%19s: %-22s -- %s','flowequation'    ,['[1x1 ' class(obj.flowequation) ']'],'flow equations'));
     1098                        disp(sprintf('%19s: %-22s -- %s','timestepping'    ,['[1x1 ' class(obj.timestepping) ']'],'time stepping for transient models'));
     1099                        disp(sprintf('%19s: %-22s -- %s','initialization'  ,['[1x1 ' class(obj.initialization) ']'],'initial guess/state'));
     1100                        disp(sprintf('%19s: %-22s -- %s','rifts'           ,['[1x1 ' class(obj.rifts) ']'],'rifts properties'));
     1101                        disp(sprintf('%19s: %-22s -- %s','debug'           ,['[1x1 ' class(obj.debug) ']'],'debugging tools (valgrind, gprof)'));
     1102                        disp(sprintf('%19s: %-22s -- %s','verbose'         ,['[1x1 ' class(obj.verbose) ']'],'verbosity level in solve'));
     1103                        disp(sprintf('%19s: %-22s -- %s','settings'        ,['[1x1 ' class(obj.settings) ']'],'settings properties'));
     1104                        disp(sprintf('%19s: %-22s -- %s','solver'          ,['[1x1 ' class(obj.solver) ']'],'PETSc options for each solution'));
     1105                        disp(sprintf('%19s: %-22s -- %s','cluster'         ,['[1x1 ' class(obj.cluster) ']'],'cluster parameters (number of cpus...)'));
     1106                        disp(sprintf('%19s: %-22s -- %s','balancethickness',['[1x1 ' class(obj.balancethickness) ']'],'parameters for balancethickness solution'));
     1107                        disp(sprintf('%19s: %-22s -- %s','diagnostic'      ,['[1x1 ' class(obj.diagnostic) ']'],'parameters for diagnostic solution'));
     1108                        disp(sprintf('%19s: %-22s -- %s','groundingline'   ,['[1x1 ' class(obj.groundingline) ']'],'parameters for groundingline solution'));
     1109                        disp(sprintf('%19s: %-22s -- %s','hydrology'       ,['[1x1 ' class(obj.hydrology) ']'],'parameters for hydrology solution'));
     1110                        disp(sprintf('%19s: %-22s -- %s','prognostic'      ,['[1x1 ' class(obj.prognostic) ']'],'parameters for prognostic solution'));
     1111                        disp(sprintf('%19s: %-22s -- %s','thermal'         ,['[1x1 ' class(obj.thermal) ']'],'parameters for thermal solution'));
     1112                        disp(sprintf('%19s: %-22s -- %s','steadystate'     ,['[1x1 ' class(obj.steadystate) ']'],'parameters for steadystate solution'));
     1113                        disp(sprintf('%19s: %-22s -- %s','transient'       ,['[1x1 ' class(obj.transient) ']'],'parameters for transient solution'));
     1114                        disp(sprintf('%19s: %-22s -- %s','autodiff'        ,['[1x1 ' class(obj.autodiff) ']'],'automatic differentiation parameters'));
     1115                        disp(sprintf('%19s: %-22s -- %s','flaim'           ,['[1x1 ' class(obj.flaim) ']'],'flaim parameters'));
     1116                        disp(sprintf('%19s: %-22s -- %s','inversion'       ,['[1x1 ' class(obj.inversion) ']'],'parameters for inverse methods'));
     1117                        disp(sprintf('%19s: %-22s -- %s','qmu'             ,['[1x1 ' class(obj.qmu) ']'],'dakota properties'));
     1118                        disp(sprintf('%19s: %-22s -- %s','results'         ,['[1x1 ' class(obj.results) ']'],'model results'));
     1119                        disp(sprintf('%19s: %-22s -- %s','radaroverlay'    ,['[1x1 ' class(obj.radaroverlay) ']'],'radar image for plot overlay'));
     1120                        disp(sprintf('%19s: %-22s -- %s','miscellaneous'   ,['[1x1 ' class(obj.miscellaneous) ']'],'miscellaneous fields'));
     1121                end % }}}
     1122        end
    11231123 end
  • issm/trunk/src/m/classes/model/model.py

    r13395 r13975  
    11#module imports {{{
    22import numpy
     3import copy
    34from mesh import mesh
    45from mask import mask
     
    3031from inversion import inversion
    3132from qmu import qmu
     33from results import results
    3234from radaroverlay import radaroverlay
    3335from miscellaneous import miscellaneous
    3436from private import private
    35 from collections import OrderedDict
    3637from EnumDefinitions import *
    3738from ismumps import *
     
    3940from iluasmoptions import *
    4041from project3d import *
     42from FlagElements import *
     43from NodeConnectivity import *
     44from ElementConnectivity import *
     45from contourenvelope import *
    4146#}}}
    4247
     
    8287                self.qmu              = qmu()
    8388
    84                 self.results          = OrderedDict()
     89                self.results          = results()
    8590                self.radaroverlay     = radaroverlay()
    8691                self.miscellaneous    = miscellaneous()
     
    167172                print ("model not consistent: %s" % string)
    168173                self.private.isconsistent=False
     174                return self
     175        # }}}
     176
     177        def extract(md,area):    # {{{
     178                """
     179                extract - extract a model according to an Argus contour or flag list
     180
     181                   This routine extracts a submodel from a bigger model with respect to a given contour
     182                   md must be followed by the corresponding exp file or flags list
     183                   It can either be a domain file (argus type, .exp extension), or an array of element flags.
     184                   If user wants every element outside the domain to be
     185                   extract2d, add '~' to the name of the domain file (ex: '~Pattyn.exp');
     186                   an empty string '' will be considered as an empty domain
     187                   a string 'all' will be considered as the entire domain
     188
     189                   Usage:
     190                      md2=extract(md,area);
     191
     192                   Examples:
     193                      md2=extract(md,'Domain.exp');
     194                      md2=extract(md,md.mask.elementonfloatingice);
     195
     196                   See also: EXTRUDE, COLLAPSE
     197                """
     198
     199                #copy model
     200                md1=copy.deepcopy(md)
     201
     202                #get elements that are inside area
     203                flag_elem=FlagElements(md1,area)
     204                if not numpy.any(flag_elem):
     205                        raise RuntimeError("extracted model is empty")
     206
     207                #kick out all elements with 3 dirichlets
     208                spc_elem=numpy.nonzero(numpy.logical_not(flag_elem))[0]
     209                spc_node=numpy.unique(md1.mesh.elements[spc_elem,:]).astype(int)-1
     210                flag=numpy.ones(md1.mesh.numberofvertices)
     211                flag[spc_node]=0
     212                pos=numpy.nonzero(numpy.logical_not(numpy.sum(flag[md1.mesh.elements.astype(int)-1],axis=1)))[0]
     213                flag_elem[pos]=0
     214
     215                #extracted elements and nodes lists
     216                pos_elem=numpy.nonzero(flag_elem)[0]
     217                pos_node=numpy.unique(md1.mesh.elements[pos_elem,:]).astype(int)-1
     218
     219                #keep track of some fields
     220                numberofvertices1=md1.mesh.numberofvertices
     221                numberofelements1=md1.mesh.numberofelements
     222                numberofvertices2=numpy.size(pos_node)
     223                numberofelements2=numpy.size(pos_elem)
     224                flag_node=numpy.zeros(numberofvertices1)
     225                flag_node[pos_node]=1
     226
     227                #Create Pelem and Pnode (transform old nodes in new nodes and same thing for the elements)
     228                Pelem=numpy.zeros(numberofelements1)
     229                Pelem[pos_elem]=numpy.arange(1,numberofelements2+1)
     230                Pnode=numpy.zeros(numberofvertices1)
     231                Pnode[pos_node]=numpy.arange(1,numberofvertices2+1)
     232
     233                #renumber the elements (some node won't exist anymore)
     234                elements_1=copy.deepcopy(md1.mesh.elements)
     235                elements_2=elements_1[pos_elem,:]
     236                elements_2[:,0]=Pnode[elements_2[:,0].astype(int)-1]
     237                elements_2[:,1]=Pnode[elements_2[:,1].astype(int)-1]
     238                elements_2[:,2]=Pnode[elements_2[:,2].astype(int)-1]
     239                if md1.mesh.dimension==3:
     240                        elements_2[:,3]=Pnode[elements_2[:,3].astype(int)-1]
     241                        elements_2[:,4]=Pnode[elements_2[:,4].astype(int)-1]
     242                        elements_2[:,5]=Pnode[elements_2[:,5].astype(int)-1]
     243
     244                #OK, now create the new model!
     245
     246                #take every field from model
     247                md2=copy.deepcopy(md1)
     248
     249                #automatically modify fields
     250
     251                #loop over model fields
     252                model_fields=vars(md1)
     253                for fieldi in model_fields:
     254                        #get field
     255                        field=getattr(md1,fieldi)
     256                        fieldsize=numpy.shape(field)
     257                        if hasattr(field,'__dict__') and not ismember(fieldi,['results'])[0]:    #recursive call
     258                                object_fields=vars(field)
     259                                for fieldj in object_fields:
     260                                        #get field
     261                                        field=getattr(getattr(md1,fieldi),fieldj)
     262                                        fieldsize=numpy.shape(field)
     263                                        if len(fieldsize):
     264                                                #size = number of nodes * n
     265                                                if   fieldsize[0]==numberofvertices1:
     266                                                        setattr(getattr(md2,fieldi),fieldj,field[pos_node,:])
     267                                                elif fieldsize[0]==numberofvertices1+1:
     268                                                        setattr(getattr(md2,fieldi),fieldj,numpy.vstack((field[pos_node,:],field[-1,:])))
     269                                                #size = number of elements * n
     270                                                elif fieldsize[0]==numberofelements1:
     271                                                        setattr(getattr(md2,fieldi),fieldj,field[pos_elem,:])
     272                        else:
     273                                if len(fieldsize):
     274                                        #size = number of nodes * n
     275                                        if   fieldsize[0]==numberofvertices1:
     276                                                setattr(md2,fieldi,field[pos_node,:])
     277                                        elif fieldsize[0]==numberofvertices1+1:
     278                                                setattr(md2,fieldi,numpy.hstack((field[pos_node,:],field[-1,:])))
     279                                        #size = number of elements * n
     280                                        elif fieldsize[0]==numberofelements1:
     281                                                setattr(md2,fieldi,field[pos_elem,:])
     282
     283                #modify some specific fields
     284
     285                #Mesh
     286                md2.mesh.numberofelements=numberofelements2
     287                md2.mesh.numberofvertices=numberofvertices2
     288                md2.mesh.elements=elements_2
     289
     290                #mesh.uppervertex mesh.lowervertex
     291                if md1.mesh.dimension==3:
     292                        md2.mesh.uppervertex=md1.mesh.uppervertex[pos_node]
     293                        pos=numpy.nonzero(numpy.logical_not(numpy.isnan(md2.mesh.uppervertex)))[0]
     294                        md2.mesh.uppervertex[pos]=Pnode[md2.mesh.uppervertex[pos].astype(int)-1]
     295
     296                        md2.mesh.lowervertex=md1.mesh.lowervertex[pos_node]
     297                        pos=numpy.nonzero(numpy.logical_not(numpy.isnan(md2.mesh.lowervertex)))[0]
     298                        md2.mesh.lowervertex[pos]=Pnode[md2.mesh.lowervertex[pos].astype(int)-1]
     299
     300                        md2.mesh.upperelements=md1.mesh.upperelements[pos_elem]
     301                        pos=numpy.nonzero(numpy.logical_not(numpy.isnan(md2.mesh.upperelements)))[0]
     302                        md2.mesh.upperelements[pos]=Pelem[md2.mesh.upperelements[pos].astype(int)-1]
     303
     304                        md2.mesh.lowerelements=md1.mesh.lowerelements[pos_elem]
     305                        pos=numpy.nonzero(numpy.logical_not(numpy.isnan(md2.mesh.lowerelements)))[0]
     306                        md2.mesh.lowerelements[pos]=Pelem[md2.mesh.lowerelements[pos].astype(int)-1]
     307
     308                #Initial 2d mesh
     309                if md1.mesh.dimension==3:
     310                        flag_elem_2d=flag_elem[numpy.arange(0,md1.mesh.numberofelements2d)]
     311                        pos_elem_2d=numpy.nonzero(flag_elem_2d)[0]
     312                        flag_node_2d=flag_node[numpy.arange(0,md1.mesh.numberofvertices2d)]
     313                        pos_node_2d=numpy.nonzero(flag_node_2d)[0]
     314
     315                        md2.mesh.numberofelements2d=numpy.size(pos_elem_2d)
     316                        md2.mesh.numberofvertices2d=numpy.size(pos_node_2d)
     317                        md2.mesh.elements2d=md1.mesh.elements2d[pos_elem_2d,:]
     318                        md2.mesh.elements2d[:,0]=Pnode[md2.mesh.elements2d[:,0].astype(int)-1]
     319                        md2.mesh.elements2d[:,1]=Pnode[md2.mesh.elements2d[:,1].astype(int)-1]
     320                        md2.mesh.elements2d[:,2]=Pnode[md2.mesh.elements2d[:,2].astype(int)-1]
     321
     322                        md2.mesh.x2d=md1.mesh.x[pos_node_2d]
     323                        md2.mesh.y2d=md1.mesh.y[pos_node_2d]
     324
     325                #Edges
     326                if len(numpy.shape(md2.mesh.edges))>1 and numpy.size(md2.mesh.edges,axis=1)>1:    #do not use ~isnan because there are some NaNs...
     327                        #renumber first two columns
     328                        pos=numpy.nonzero(md2.mesh.edges[:,3]!=-1)[0]
     329                        md2.mesh.edges[:  ,0]=Pnode[md2.mesh.edges[:,0].astype(int)-1]
     330                        md2.mesh.edges[:  ,1]=Pnode[md2.mesh.edges[:,1].astype(int)-1]
     331                        md2.mesh.edges[:  ,2]=Pelem[md2.mesh.edges[:,2].astype(int)-1]
     332                        md2.mesh.edges[pos,3]=Pelem[md2.mesh.edges[pos,3].astype(int)-1]
     333                        #remove edges when the 2 vertices are not in the domain.
     334                        md2.mesh.edges=md2.mesh.edges[numpy.nonzero(numpy.logical_and(md2.mesh.edges[:,0],md2.mesh.edges[:,1]))[0],:]
     335                        #Replace all zeros by -1 in the last two columns
     336                        pos=numpy.nonzero(md2.mesh.edges[:,2]==0)[0]
     337                        md2.mesh.edges[pos,2]=-1
     338                        pos=numpy.nonzero(md2.mesh.edges[:,3]==0)[0]
     339                        md2.mesh.edges[pos,3]=-1
     340                        #Invert -1 on the third column with last column (Also invert first two columns!!)
     341                        pos=numpy.nonzero(md2.mesh.edges[:,2]==-1)[0]
     342                        md2.mesh.edges[pos,2]=md2.mesh.edges[pos,3]
     343                        md2.mesh.edges[pos,3]=-1
     344                        values=md2.mesh.edges[pos,1]
     345                        md2.mesh.edges[pos,1]=md2.mesh.edges[pos,0]
     346                        md2.mesh.edges[pos,0]=values
     347                        #Finally remove edges that do not belong to any element
     348                        pos=numpy.nonzero(numpy.logical_and(md2.mesh.edges[:,1]==-1,md2.mesh.edges[:,2]==-1))[0]
     349                        md2.mesh.edges=numpy.delete(md2.mesh.edges,pos,axis=0)
     350
     351                #Penalties
     352                if numpy.any(numpy.logical_not(numpy.isnan(md2.diagnostic.vertex_pairing))):
     353                        for i in xrange(numpy.size(md1.diagnostic.vertex_pairing,axis=0)):
     354                                md2.diagnostic.vertex_pairing[i,:]=Pnode[md1.diagnostic.vertex_pairing[i,:]]
     355                        md2.diagnostic.vertex_pairing=md2.diagnostic.vertex_pairing[numpy.nonzero(md2.diagnostic.vertex_pairing[:,0])[0],:]
     356                if numpy.any(numpy.logical_not(numpy.isnan(md2.prognostic.vertex_pairing))):
     357                        for i in xrange(numpy.size(md1.prognostic.vertex_pairing,axis=0)):
     358                                md2.prognostic.vertex_pairing[i,:]=Pnode[md1.prognostic.vertex_pairing[i,:]]
     359                        md2.prognostic.vertex_pairing=md2.prognostic.vertex_pairing[numpy.nonzero(md2.prognostic.vertex_pairing[:,0])[0],:]
     360
     361                #recreate segments
     362                if md1.mesh.dimension==2:
     363                        [md2.mesh.vertexconnectivity]=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices)
     364                        [md2.mesh.elementconnectivity]=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity)
     365                        md2.mesh.segments=contourenvelope(md2)
     366                        md2.mesh.vertexonboundary=numpy.zeros(numberofvertices2)
     367                        md2.mesh.vertexonboundary[md2.mesh.segments[:,0:2].astype(int)-1]=1
     368                else:
     369                        #First do the connectivity for the contourenvelope in 2d
     370                        [md2.mesh.vertexconnectivity]=NodeConnectivity(md2.mesh.elements2d,md2.mesh.numberofvertices2d)
     371                        [md2.mesh.elementconnectivity]=ElementConnectivity(md2.mesh.elements2d,md2.mesh.vertexconnectivity)
     372                        md2.mesh.segments=contourenvelope(md2)
     373                        md2.mesh.vertexonboundary=numpy.zeros(numberofvertices2/md2.mesh.numberoflayers)
     374                        md2.mesh.vertexonboundary[md2.mesh.segments[:,0:2].astype(int)-1]=1
     375                        md2.mesh.vertexonboundary=numpy.tile(md2.mesh.vertexonboundary,md2.mesh.numberoflayers)
     376                        #Then do it for 3d as usual
     377                        [md2.mesh.vertexconnectivity]=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices)
     378                        [md2.mesh.elementconnectivity]=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity)
     379
     380                #Boundary conditions: Dirichlets on new boundary
     381                #Catch the elements that have not been extracted
     382                orphans_elem=numpy.nonzero(numpy.logical_not(flag_elem))[0]
     383                orphans_node=numpy.unique(md1.mesh.elements[orphans_elem,:]).astype(int)-1
     384                #Figure out which node are on the boundary between md2 and md1
     385                nodestoflag1=numpy.intersect1d(orphans_node,pos_node)
     386                nodestoflag2=Pnode[nodestoflag1].astype(int)-1
     387                if numpy.size(md1.diagnostic.spcvx)>1 and numpy.size(md1.diagnostic.spcvy)>2 and numpy.size(md1.diagnostic.spcvz)>2:
     388                        if numpy.size(md1.inversion.vx_obs)>1 and numpy.size(md1.inversion.vy_obs)>1:
     389                                md2.diagnostic.spcvx[nodestoflag2]=md2.inversion.vx_obs[nodestoflag2]
     390                                md2.diagnostic.spcvy[nodestoflag2]=md2.inversion.vy_obs[nodestoflag2]
     391                        else:
     392                                md2.diagnostic.spcvx[nodestoflag2]=float('NaN')
     393                                md2.diagnostic.spcvy[nodestoflag2]=float('NaN')
     394                                print "\n!! extract warning: spc values should be checked !!\n\n"
     395                        #put 0 for vz
     396                        md2.diagnostic.spcvz[nodestoflag2]=0
     397                if numpy.any(numpy.logical_not(numpy.isnan(md1.thermal.spctemperature))):
     398                        md2.thermal.spctemperature[nodestoflag2,0]=1
     399
     400                #Diagnostic
     401                if numpy.any(numpy.logical_not(numpy.isnan(md2.diagnostic.icefront))):
     402                        md2.diagnostic.icefront[:,0]=Pnode[md1.diagnostic.icefront[:,0].astype(int)-1]
     403                        md2.diagnostic.icefront[:,1]=Pnode[md1.diagnostic.icefront[:,1].astype(int)-1]
     404                        md2.diagnostic.icefront[:,-2]=Pelem[md1.diagnostic.icefront[:,-2].astype(int)-1]
     405                        if md1.mesh.dimension==3:
     406                                md2.diagnostic.icefront[:,2]=Pnode[md1.diagnostic.icefront[:,2].astype(int)-1]
     407                                md2.diagnostic.icefront[:,3]=Pnode[md1.diagnostic.icefront[:,3].astype(int)-1]
     408                        md2.diagnostic.icefront=md2.diagnostic.icefront[numpy.nonzero(numpy.logical_and(numpy.logical_and(md2.diagnostic.icefront[:,0],md2.diagnostic.icefront[:,1]),md2.diagnostic.icefront[:,-1]))[0],:]
     409
     410                #Results fields
     411                if md1.results:
     412                        md2.results=results()
     413                        for solutionfield,field in md1.results.__dict__.iteritems():
     414                                if   isinstance(field,list):
     415                                        setattr(md2.results,solutionfield,[])
     416                                        #get time step
     417                                        for i,fieldi in enumerate(field):
     418                                                if isinstance(fieldi,results) and fieldi:
     419                                                        getattr(md2.results,solutionfield).append(results())
     420                                                        fieldr=getattr(md2.results,solutionfield)[i]
     421                                                        #get subfields
     422                                                        for solutionsubfield,subfield in fieldi.__dict__.iteritems():
     423                                                                if   numpy.size(subfield)==numberofvertices1:
     424                                                                        setattr(fieldr,solutionsubfield,subfield[pos_node])
     425                                                                elif numpy.size(subfield)==numberofelements1:
     426                                                                        setattr(fieldr,solutionsubfield,subfield[pos_elem])
     427                                                                else:
     428                                                                        setattr(fieldr,solutionsubfield,subfield)
     429                                                else:
     430                                                        getattr(md2.results,solutionfield).append(None)
     431                                elif isinstance(field,results):
     432                                        setattr(md2.results,solutionfield,results())
     433                                        if isinstance(field,results) and field:
     434                                                fieldr=getattr(md2.results,solutionfield)
     435                                                #get subfields
     436                                                for solutionsubfield,subfield in field.__dict__.iteritems():
     437                                                        if   numpy.size(subfield)==numberofvertices1:
     438                                                                setattr(fieldr,solutionsubfield,subfield[pos_node])
     439                                                        elif numpy.size(subfield)==numberofelements1:
     440                                                                setattr(fieldr,solutionsubfield,subfield[pos_elem])
     441                                                        else:
     442                                                                setattr(fieldr,solutionsubfield,subfield)
     443
     444                #Keep track of pos_node and pos_elem
     445                md2.mesh.extractedvertices=pos_node.astype(float)+1
     446                md2.mesh.extractedelements=pos_elem.astype(float)+1
     447
     448                return md2
    169449        # }}}
    170450
     
    242522                        y3d=numpy.concatenate((y3d,md.mesh.y))
    243523                        #nodes are distributed between bed and surface accordingly to the given exponent
    244                         z3d=numpy.concatenate((z3d,bed3d+thickness3d*extrusionlist[i]))
     524                        z3d=numpy.concatenate((z3d,(bed3d+thickness3d*extrusionlist[i]).reshape(-1)))
    245525                number_nodes3d=numpy.size(x3d)    #number of 3d nodes for the non extruded part of the mesh
    246526
     
    402682                #Put lithostatic pressure if there is an existing pressure
    403683                if not numpy.any(numpy.isnan(md.initialization.pressure)):
    404                         md.initialization.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z)
     684                        md.initialization.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z.reshape(-1,1))
    405685
    406686                #special for thermal modeling:
  • issm/trunk/src/m/classes/modellist.m

    r13395 r13975  
    271271                        end
    272272
    273 
    274273                        %now, tar all the files and then erase them.
    275274                        eval(['!find -iname ''' name '-*'' > file_list.txt']);
     
    302301
    303302%First try and figure out if there is a special script for this particular cluster
    304 function_name=['BuildMultipleQueueingScript' cluster];
     303function_name=['BuildMultipleQueueingScript' cluster]
    305304
    306305%some specific treatment of identical cluster, gemini, castor and pollux
     
    348347
    349348%First try and figure out if there is a special script for thie particular cluster
    350 function_name=['LaunchMultipleQueueJob' cluster];
     349function_name=['LaunchMultipleQueueJob' cluster]
    351350
    352351%some specific treatment of identical cluster, gemini, castor and pollux
     
    369368%      LaunchMultipleQueueJobgemini(cluster,name,executionpath)
    370369
    371 
    372370%first, check we have the binary file and the queueing script
    373371if ~exist([ name '.queue'],'file'),
  • issm/trunk/src/m/classes/organizer.m

    r12706 r13975  
    1010%      org = organizer(varargin)
    1111%
    12 %
    1312%   Examples:
    1413%      org = organizer('repository','Models/','prefix','AGU2015','steps',0);  %build an empty organizer object with a given repository
     
    1615classdef organizer
    1716    properties (SetAccess=private)
    18                  % {{{
    19                  currentstep   =0;
    20          end
     17                % {{{
     18                currentstep   =0;
     19        end
    2120    properties (SetAccess=public)
    22                  repository    ='./';
    23                  prefix        ='model.';
    24                  trunkprefix   ='';
    25                  steps         =[];
    26                  requestedsteps=[0];
    27                  %}}}
    28          end
    29          methods
    30                  function org=organizer(varargin) % {{{
     21                repository    ='./';
     22                prefix        ='model.';
     23                trunkprefix   ='';
     24                steps         =[];
     25                requestedsteps=[0];
     26                %}}}
     27        end
     28        methods
     29                function org=organizer(varargin) % {{{
    3130
    32                          %process options
    33                          options=pairoptions(varargin{:});
     31                        %process options
     32                        options=pairoptions(varargin{:});
    3433
    35                          %Get prefix
    36                          prefix=getfieldvalue(options,'prefix','model.');
    37                          if ~ischar(prefix),                            error('prefix is not a string'); end
    38                          if ~strcmp(regexprep(prefix,'\s+',''),prefix), error('prefix should not have any white space'); end
    39                          org.prefix=prefix;
     34                        %Get prefix
     35                        prefix=getfieldvalue(options,'prefix','model.');
     36                        if ~ischar(prefix),                            error('prefix is not a string'); end
     37                        if ~strcmp(regexprep(prefix,'\s+',''),prefix), error('prefix should not have any white space'); end
     38                        org.prefix=prefix;
    4039
    41                          %Get repository
    42                          repository=getfieldvalue(options,'repository','./');
    43                          if ~ischar(repository),        error('repository is not a string'); end
    44                          if exist(repository,'dir')~=7, error(['Directory ' repository ' not found']), end
    45                          org.repository=repository;
     40                        %Get repository
     41                        repository=getfieldvalue(options,'repository','./');
     42                        if ~ischar(repository),        error('repository is not a string'); end
     43                        if exist(repository,'dir')~=7, error(['Directory ' repository ' not found']), end
     44                        org.repository=repository;
    4645
    47                          %Get repository
    48                          org.requestedsteps=getfieldvalue(options,'steps',0);
     46                        %Get steps
     47                        org.requestedsteps=getfieldvalue(options,'steps',0);
    4948
    50                          %Get trunk prefix (only if provided by user)
    51                          if exist(options,'trunkprefix'),
    52                                  trunkprefix=getfieldvalue(options,'trunkprefix','');
    53                                  if ~ischar(trunkprefix),                                 error('trunkprefix is not a string'); end
    54                                  if ~strcmp(regexprep(trunkprefix,'\s+',''),trunkprefix), error('trunkprefix should not have any white space'); end
    55                                  org.trunkprefix=trunkprefix;
    56                          end
    57                  end
    58                  %}}}
    59                  function disp(org) % {{{
    60                          disp(sprintf('   Repository: ''%s''',org.repository));
    61                          disp(sprintf('   Prefix:     ''%s''',org.prefix));
    62                          if isempty(org.steps)
    63                                  disp('   no step');
    64                          else
    65                                  for i=1:length(org.steps),
    66                                          disp(sprintf('   step #%2i: ''%s''',org.steps(i).id,org.steps(i).string));
    67                                  end
    68                          end
    69                  end
    70                  %}}}
    71                  function md=load(org,string),% {{{
     49                        %Get trunk prefix (only if provided by user)
     50                        if exist(options,'trunkprefix'),
     51                                trunkprefix=getfieldvalue(options,'trunkprefix','');
     52                                if ~ischar(trunkprefix),                                 error('trunkprefix is not a string'); end
     53                                if ~strcmp(regexprep(trunkprefix,'\s+',''),trunkprefix), error('trunkprefix should not have any white space'); end
     54                                org.trunkprefix=trunkprefix;
     55                        end
     56                end
     57                %}}}
     58                function disp(org) % {{{
     59                        disp(sprintf('   Repository: ''%s''',org.repository));
     60                        disp(sprintf('   Prefix:     ''%s''',org.prefix));
     61                        if isempty(org.steps)
     62                                disp('   no step');
     63                        else
     64                                for i=1:length(org.steps),
     65                                        disp(sprintf('   step #%2i: ''%s''',org.steps(i).id,org.steps(i).string));
     66                                end
     67                        end
     68                end
     69                %}}}
     70                function md=load(org,string),% {{{
    7271
    73                          %Get model path
    74                          if ~ischar(string), error('argument provided is not a string'); end
    75                          path=[org.repository '/' org.prefix string];
     72                        %Get model path
     73                        if ~ischar(string), error('argument provided is not a string'); end
     74                        path=[org.repository '/' org.prefix string];
    7675
    77                          %figure out if the model is there
    78                          if exist(path,'file'),
    79                                  struc=load(path,'-mat');
    80                                  name=char(fieldnames(struc));
    81                                  md=struc.(name);
    82                                  if nargout,
    83                                          varargout{1}=md;
    84                                  end
    85                          else
    86                                  error(['Could not find ' path ]);
    87                          end
    88                  end%}}}
    89                  function md=loadmodel(org,string),% {{{
     76                        %figure out if the model is there
     77                        if exist(path,'file'),
     78                                struc=load(path,'-mat');
     79                                name=char(fieldnames(struc));
     80                                md=struc.(name);
     81                                if nargout,
     82                                        varargout{1}=md;
     83                                end
     84                        else
     85                                error(['Could not find ' path ]);
     86                        end
     87                end%}}}
     88                function md=loadmodel(org,string),% {{{
    9089
    91                          %Get model path
    92                          if ~ischar(string), error('argument provided is not a string'); end
    93                          path=[org.repository '/' org.prefix string];
     90                        %Get model path
     91                        if ~ischar(string), error('argument provided is not a string'); end
     92                        path=[org.repository '/' org.prefix string];
    9493
    95                          %figure out if the model is there, otherwise, we have to use the default path supplied by user.
    96                          if exist(path,'file') | exist([path '.mat'],'file'),
    97                                  md=loadmodel(path);
    98                                  return;
    99                          end
     94                        %figure out if the model is there, otherwise, we have to use the default path supplied by user.
     95                        if exist(path,'file') | exist([path '.mat'],'file'),
     96                                md=loadmodel(path);
     97                                return;
     98                        end
    10099
    101                          %If we are here, the model has not been found. Try trunk prefix if provided
    102                          if ~isempty(org.trunkprefix),
    103                                  path2=[org.repository '/' org.trunkprefix string];
    104                                  if ~exist(path2,'file'),
    105                                          error(['Could neither find ' path ', nor ' path2]);
    106                                  else
    107                                          disp(['--> Branching ' org.prefix ' from trunk ' org.trunkprefix]);
    108                                          md=loadmodel(path2);
    109                                          return;
    110                                  end
    111                          else
    112                                  error(['Could not find ' path ]);
    113                          end
    114                  end%}}}
    115                  function bool=perform(org,string) % {{{
    116                          
    117                          bool=false;
     100                        %If we are here, the model has not been found. Try trunk prefix if provided
     101                        if ~isempty(org.trunkprefix),
     102                                path2=[org.repository '/' org.trunkprefix string];
     103                                if ~exist(path2,'file'),
     104                                        error(['Could find neither ' path ', nor ' path2]);
     105                                else
     106                                        disp(['--> Branching ' org.prefix ' from trunk ' org.trunkprefix]);
     107                                        md=loadmodel(path2);
     108                                        return;
     109                                end
     110                        else
     111                                error(['Could not find ' path ]);
     112                        end
     113                end%}}}
     114                function bool=perform(org,string) % {{{
    118115
    119                          %Some checks
    120                          if ~ischar(string),                            error('Step provided should be a string'); end
    121                          if ~strcmp(regexprep(string,'\s+',''),string), error('Step provided should not have any white space'); end
    122                          if (org.currentstep>0 & ismember({string},{org.steps.string}))
    123                                  error(['Step ' string ' already present. Change name']);
    124                          end
     116                        bool=false;
    125117
    126                          %Add step
    127                          org.steps(end+1).id=length(org.steps)+1;
    128                          org.steps(end).string=string;
    129                          org.currentstep=org.currentstep+1;
     118                        %Some checks
     119                        if ~ischar(string),                            error('Step provided should be a string'); end
     120                        if ~strcmp(regexprep(string,'\s+',''),string), error('Step provided should not have any white space'); end
     121                        if (org.currentstep>0 & ismember({string},{org.steps.string}))
     122                                error(['Step ' string ' already present. Change name']);
     123                        end
    130124
    131                          %if requestedsteps = 0, print all steps in org
    132                          if any(org.requestedsteps==0),
    133                                  if org.currentstep==1,
    134                                          disp(sprintf('   prefix: %s',org.prefix));
    135                                  end
    136                                  disp(sprintf('   step #%2i : %s',org.steps(org.currentstep).id,org.steps(org.currentstep).string));
    137                          end
     125                        %Add step
     126                        org.steps(end+1).id=length(org.steps)+1;
     127                        org.steps(end).string=string;
     128                        org.currentstep=org.currentstep+1;
    138129
    139                          %Ok, now if currentstep is a member of steps, return true
    140                          if ismember(org.currentstep,org.requestedsteps),
    141                                  disp(sprintf('\n   step #%i : %s\n',org.steps(org.currentstep).id,org.steps(org.currentstep).string));
    142                                  bool=true;
    143                          end
     130                        %if requestedsteps = 0, print all steps in org
     131                        if any(org.requestedsteps==0),
     132                                if org.currentstep==1,
     133                                        disp(sprintf('   prefix: %s',org.prefix));
     134                                end
     135                                disp(sprintf('   step #%2i : %s',org.steps(org.currentstep).id,org.steps(org.currentstep).string));
     136                        end
    144137
    145                          %assign org back to calling workspace
    146                          assignin('caller',inputname(1),org);
     138                        %Ok, now if currentstep is a member of steps, return true
     139                        if ismember(org.currentstep,org.requestedsteps),
     140                                disp(sprintf('\n   step #%i : %s\n',org.steps(org.currentstep).id,org.steps(org.currentstep).string));
     141                                bool=true;
     142                        end
    147143
    148                  end%}}}
    149                  function savemodel(org,md) % {{{
     144                        %assign org back to calling workspace
     145                        assignin('caller',inputname(1),org);
    150146
    151                          %check
    152                          if (org.currentstep==0), error('Cannot save model because organizer (org) is empty! Make sure you did not skip any perform call'); end
    153                          if (org.currentstep>length(org.steps)), error('Cannot save model because organizer (org) is not up to date!'); end
     147                end%}}}
     148                function savemodel(org,md) % {{{
    154149
    155                          name=[org.repository '/' org.prefix org.steps(org.currentstep).string ];
    156                          disp(['saving model as: ' name]);
    157                          
    158                          %check that md is a model
    159                          if ~isa(md,'model'), warning('third argument is not a model'); end
    160                          if (org.currentstep>length(org.steps)), error(['organizer error message: element with id ' num2str(org.currentstep) ' not found']); end
     150                        %check
     151                        if (org.currentstep==0), error('Cannot save model because organizer (org) is empty! Make sure you did not skip any perform call'); end
     152                        if (org.currentstep>length(org.steps)), error('Cannot save model because organizer (org) is not up to date!'); end
    161153
    162                          %save model
    163                          save(name,'md','-v7.3');
    164                  end%}}}
     154                        name=[org.repository '/' org.prefix org.steps(org.currentstep).string ];
     155                        disp(['saving model as: ' name]);
     156
     157                        %check that md is a model
     158                        if ~isa(md,'model'), warning('second argument is not a model'); end
     159                        if (org.currentstep>length(org.steps)), error(['organizer error message: element with id ' num2str(org.currentstep) ' not found']); end
     160
     161                        %save model
     162                        save(name,'md','-v7.3');
     163                end%}}}
    165164        end
    166165end
  • issm/trunk/src/m/classes/pairoptions.m

    r12706 r13975  
    175175
    176176                        %some argument checking:
    177                         if nargin~=2 & nargin~=3,
     177                        if nargin~=2 && nargin~=3,
    178178                                help getfieldvalue
    179179                                error('getfieldvalue error message: bad usage');
     
    185185
    186186                        %Recover option
    187                         for i=1:size(obj.list,1),
    188                                 if strcmpi(obj.list{i,1},field)
    189                                         value=obj.list{i,2};
    190                                         return
    191                                 end
     187                        pos=find(strcmpi(obj.list(:,1),field));
     188                        if ~isempty(pos),
     189                                value=obj.list{pos(1),2}; %ignore extra entry
     190                                return;
    192191                        end
    193192
  • issm/trunk/src/m/classes/pairoptions.py

    r13395 r13975  
    4141                        else:
    4242                                #option is not a string, ignore it
    43                                 print "WARNING: option number %d '%s' is not a string and will be ignored." % (i+1,type(arg[2*i]))
     43                                print "WARNING: option number %d is not a string and will be ignored." % (i+1)
    4444        # }}}
    4545
     
    5353
    5454        def addfielddefault(self,field,value):    # {{{
    55                 """ADDFIELDDEFAULT - add a field to an options list if it does not exist"""
     55                """ADDFIELDDEFAULT - add a field to an options list if it does not already exist"""
    5656                if isinstance(field,(str,unicode)):
    5757                        if field not in self.list:
     
    128128        # }}}
    129129
    130 #       function num = fieldoccurences(obj,field), % {{{
    131 #       %FIELDOCCURENCES - get number of occurence of a field
    132 #
    133 #               %check input
    134 #               if ~ischar(field),
    135 #                       error('fieldoccurences error message: field should be a string');
    136 #               end
    137 #
    138 #               %get number of occurence
    139 #               num=sum(strcmpi(field,obj.list(:,1)));
    140 #       end % }}}
     130        #def fieldoccurences(self,field): #{{{
     131        #       '''
     132        #       FIELDOCCURENCES - get number of occurence of a field
     133        #       '''
     134        #
     135        #       #check input
     136        #       if not isinstance(field,(str,unicode)):
     137        #               raise TypeError("fieldoccurences error message: field should be a string")
     138
     139        #       #get number of occurence
     140        #       # ??
     141        #       #return num
     142        #       #% }}}
    141143
    142144        def getfieldvalue(self,field,default=None):    # {{{
  • issm/trunk/src/m/classes/planetmesh.m

    r13395 r13975  
    1717                numberofelements            = 0;
    1818                numberofvertices            = 0;
    19                
     19
    2020                lat                         = NaN
    2121                long                        = NaN
     
    103103                        fielddisplay(obj,'dimension','planetmesh dimension (2d or 3d)');
    104104                        fielddisplay(obj,'numberoflayers','number of extrusion layers');
    105                        
     105
    106106                        fielddisplay(obj,'vertexconnectivity','list of vertices connected to vertex_i');
    107107                        fielddisplay(obj,'elementconnectivity','list of vertices connected to element_i');
  • issm/trunk/src/m/classes/prognostic.m

    r13395 r13975  
    1212                 vertex_pairing         = NaN;
    1313                 penalty_factor         = 0;
     14                 requested_outputs      = NaN;
    1415        end
    1516        methods
     
    4546                        md = checkfield(md,'prognostic.stabilization','values',[0 1 2 3]);
    4647                        md = checkfield(md,'prognostic.min_thickness','>',0);
     48                        if ~isempty(md.prognostic.requested_outputs),
     49                                md = checkfield(md,'prognostic.requested_outputs','size',[NaN 1]);
     50                        end
    4751
    4852                end % }}}
     
    5761                        fielddisplay(obj,'penalty_factor','offset used by penalties: penalty = Kmax*10^offset');
    5862                        fielddisplay(obj,'vertex_pairing','pairs of vertices that are penalized');
     63                        fielddisplay(obj,'requested_outputs','additional outputs requested');
    5964
    6065                end % }}}
     
    6671                        WriteData(fid,'object',obj,'fieldname','vertex_pairing','format','DoubleMat','mattype',3);
    6772                        WriteData(fid,'object',obj,'fieldname','penalty_factor','format','Double');
     73                        WriteData(fid,'object',obj,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
    6874                end % }}}
    6975        end
  • issm/trunk/src/m/classes/prognostic.py

    r13395 r13975  
    2323                self.vertex_pairing         = float('NaN')
    2424                self.penalty_factor         = 0
     25                self.requested_outputs      = float('NaN')
    2526
    2627                #set defaults
     
    3536                string="%s\n%s"%(string,fielddisplay(self,'hydrostatic_adjustment','adjustment of ice shelves surface and bed elevations: ''Incremental'' or ''Absolute'' '))
    3637                string="%s\n%s"%(string,fielddisplay(self,'stabilization','0->no, 1->artificial_diffusivity, 2->streamline upwinding, 3->discontinuous Galerkin'))
     38                string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
    3739
    3840                return string
     
    6769                md = checkfield(md,'prognostic.stabilization','values',[0,1,2,3])
    6870                md = checkfield(md,'prognostic.min_thickness','>',0)
     71                if not md.prognostic.requested_outputs:
     72                        md = checkfield(md,'prognostic.requested_outputs','size',[float('NaN'),1])
    6973
    7074                return md
     
    7882                WriteData(fid,'object',self,'fieldname','vertex_pairing','format','DoubleMat','mattype',3)
    7983                WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
     84                WriteData(fid,'object',self,'fieldname','requested_outputs','format','DoubleMat','mattype',3);
    8085        # }}}
    8186
  • issm/trunk/src/m/classes/qmu.m

    r13395 r13975  
    3333                end % }}}
    3434                function obj = setdefaultparameters(obj) % {{{
    35        
     35
    3636                end % }}}
    3737                function md = checkconsistency(obj,md,solution,analyses) % {{{
     
    142142                function marshall(obj,fid) % {{{
    143143                        WriteData(fid,'object',obj,'fieldname','isdakota','format','Boolean');
    144                         if ~obj.isdakota, return; end
     144                        if ~obj.isdakota,
     145                                WriteData(fid,'data',false,'enum',QmuMassFluxSegmentsPresentEnum,'format','Boolean');
     146                                return;
     147                        end
    145148                        WriteData(fid,'object',obj,'fieldname','partition','format','DoubleMat','mattype',2);
    146149                        WriteData(fid,'object',obj,'fieldname','numberofpartitions','format','Integer');
     
    148151                        WriteData(fid,'object',obj,'fieldname','variabledescriptors','format','StringArray');
    149152                        WriteData(fid,'object',obj,'fieldname','responsedescriptors','format','StringArray');
    150                         WriteData(fid,'object',obj,'fieldname','mass_flux_segments','format','MatArray');
     153                        if ~isempty(obj.mass_flux_segments),
     154                                WriteData(fid,'data',obj.mass_flux_segments,'enum',MassFluxSegmentsEnum,'format','MatArray');
     155                                flag=true;
     156                        else
     157                                flag=false;
     158                        end
     159                        WriteData(fid,'data',flag,'enum',QmuMassFluxSegmentsPresentEnum,'format','Boolean');
    151160                end % }}}
    152161        end
  • issm/trunk/src/m/classes/qmu.py

    r13395 r13975  
    4545                return self
    4646        #}}}
    47 
    4847        def checkconsistency(self,md,solution,analyses):    # {{{
    4948
     
    6867                return md
    6968        # }}}
    70 
    7169        def __repr__(self):    # {{{
    7270                s ='   qmu parameters:\n'
     
    141139                return s
    142140        # }}}
    143                
    144141        def marshall(self,fid):    # {{{
    145142                WriteData(fid,'object',self,'fieldname','isdakota','format','Boolean')
    146143                if not self.isdakota:
     144                        WriteData(fid,'data',False,'enum',QmuMassFluxSegmentsPresentEnum(),'format','Boolean');
    147145                        return
    148146                WriteData(fid,'object',self,'fieldname','partition','format','DoubleMat','mattype',2)
     
    151149                WriteData(fid,'object',self,'fieldname','variabledescriptors','format','StringArray')
    152150                WriteData(fid,'object',self,'fieldname','responsedescriptors','format','StringArray')
    153                 WriteData(fid,'object',self,'fieldname','mass_flux_segments','format','MatArray')
     151                if not self.mass_flux_segments:
     152                        WriteData(fid,'data',self.mass_flux_segments,'enum',MassFluxSegmentsEnum(),'format','MatArray');
     153                        flag=True;
     154                else:
     155                        flag=False;
     156                WriteData(fid,'data',flag,'enum',QmuMassFluxSegmentsPresentEnum(),'format','Boolean');
    154157        # }}}
    155158
  • issm/trunk/src/m/classes/qmu/@dakota_method/dakota_method.m

    r3094 r13975  
    4949        params   =struct();
    5050    end
    51    
     51
    5252    methods
    5353        function [dm]=dakota_method(method)
     
    828828
    829829                    end
    830                    
     830
    831831%  if more than one argument, issue warning
    832832
     
    852852                disp(sprintf('    responses: %s'      ,string_cell(dm(i).responses)));
    853853                disp(sprintf('       ghspec: %s\n'    ,string_cell(dm(i).ghspec)));
    854    
     854
    855855%  display the parameters within the object
    856856
     
    860860                    maxlen=max(maxlen,length(fnames{j}));
    861861                end
    862    
     862
    863863                for j=1:numel(fnames)
    864864                    disp(sprintf(['       params.%-' num2str(maxlen+1) 's: %s'],...
     
    870870    end
    871871end
    872 
  • issm/trunk/src/m/classes/qmu/@dakota_method/dmeth_params_write.m

    r5424 r13975  
    4646                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
    4747        end
    48        
     48
    4949    case {'npsol'}
    5050        param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
     
    6464                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
    6565        end
    66        
     66
    6767    case {'conmin'}
    6868        param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
     
    8080                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
    8181        end
    82        
     82
    8383    case {'optpp'}
    8484        param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
     
    120120                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
    121121        end
    122        
     122
    123123    case {'apps'}
    124124        param_write(fid,sbeg,'max_function_evaluations',' = ','\n',dm.params);
     
    140140                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
    141141        end
    142        
     142
    143143    case {'coliny'}
    144144        param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
     
    212212                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
    213213        end
    214        
     214
    215215    case {'ncsu'}
    216216        param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
     
    226226                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
    227227        end
    228        
     228
    229229    case {'jega'}
    230230        param_write(fid,sbeg,'max_iterations','           = ','\n',dm.params);
     
    282282                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
    283283        end
    284        
     284
    285285    case {'lsq'}
    286286        switch dm.method
     
    344344                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
    345345        end
    346        
     346
    347347    case {'nond'}
    348348        switch dm.method
     
    426426                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
    427427        end
    428        
     428
    429429    case {'dace'}
    430430        switch dm.method
     
    484484                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
    485485        end
    486        
     486
    487487    case {'param'}
    488488        param_write(fid,sbeg,'output',' ','\n',dm.params);
     
    512512            case {'multidim_parameter_study'}
    513513                param_write(fid,sbeg,'partitions',' = ','\n',dm.params);
    514            
     514
    515515            otherwise
    516516                error('Unrecognized ''%s'' method: ''%s''.',dm.type,dm.method);
  • issm/trunk/src/m/classes/qmu/continuous_design.m

    r9548 r13975  
    3939        scale     = 1.;
    4040    end
    41    
     41
    4242    methods
    4343        function [cdv]=continuous_design(varargin)
     
    6565                    cdv(asizec{:})=continuous_design;
    6666                    clear asizec
    67                    
     67
    6868                    if ischar(varargin{1})
    6969                        varargin{1}=cellstr(varargin{1});
     
    212212        end
    213213    end
    214    
     214
    215215    methods (Static)
    216216        function []=dakota_write(fidi,dvar)
  • issm/trunk/src/m/classes/qmu/continuous_state.m

    r9548 r13975  
    3535        upper     = Inf;
    3636    end
    37    
     37
    3838    methods
    3939        function [csv]=continuous_state(varargin)
     
    6161                    csv(asizec{:})=continuous_state;
    6262                    clear asizec
    63                    
     63
    6464                    if ischar(varargin{1})
    6565                        varargin{1}=cellstr(varargin{1});
     
    177177        end
    178178    end
    179    
     179
    180180    methods (Static)
    181181        function []=dakota_write(fidi,dvar)
  • issm/trunk/src/m/classes/qmu/least_squares_term.m

    r9548 r13975  
    3535        weight    = 1.;
    3636    end
    37    
     37
    3838    methods
    3939        function [lst]=least_squares_term(varargin)
     
    5454                        lst(asizec{:})=least_squares_term;
    5555                        clear asizec
    56                    
     56
    5757                        if ischar(varargin{1})
    5858                            varargin{1}=cellstr(varargin{1});
     
    169169        end
    170170    end
    171    
     171
    172172    methods (Static)
    173173        function [rdesc]=dakota_write(fidi,dresp,rdesc)
  • issm/trunk/src/m/classes/qmu/linear_equality_constraint.m

    r9548 r13975  
    3535        scale     = 1.;
    3636    end
    37    
     37
    3838    methods
    3939        function [lec]=linear_equality_constraint(varargin)
     
    6969                    lec(asizec{:})=linear_equality_constraint;
    7070                    clear asizec
    71                    
     71
    7272                    for i=1:numel(lec)
    7373                        if (size(varargin{1},1) > 1)
     
    167167        end
    168168    end
    169    
     169
    170170    methods (Static)
    171171        function []=dakota_write(fidi,dvar)
  • issm/trunk/src/m/classes/qmu/linear_inequality_constraint.m

    r9548 r13975  
    3737        scale     = 1.;
    3838    end
    39    
     39
    4040    methods
    4141        function [lic]=linear_inequality_constraint(varargin)
     
    7777                    lic(asizec{:})=linear_inequality_constraint;
    7878                    clear asizec
    79                    
     79
    8080                    for i=1:numel(lic)
    8181                        if (size(varargin{1},1) > 1)
     
    189189        end
    190190    end
    191    
     191
    192192    methods (Static)
    193193        function []=dakota_write(fidi,dvar)
     
    203203    end
    204204end
    205 
  • issm/trunk/src/m/classes/qmu/nonlinear_equality_constraint.m

    r9548 r13975  
    3535        scale     = 1.;
    3636    end
    37    
     37
    3838    methods
    3939        function [nec]=nonlinear_equality_constraint(varargin)
     
    6161                    nec(asizec{:})=nonlinear_equality_constraint;
    6262                    clear asizec
    63                    
     63
    6464                    if ischar(varargin{1})
    6565                        varargin{1}=cellstr(varargin{1});
     
    171171        end
    172172    end
    173    
     173
    174174    methods (Static)
    175175        function [rdesc]=dakota_write(fidi,dresp,rdesc)
  • issm/trunk/src/m/classes/qmu/nonlinear_inequality_constraint.m

    r9548 r13975  
    3737        scale     = 1.;
    3838    end
    39    
     39
    4040    methods
    4141        function [nic]=nonlinear_inequality_constraint(varargin)
     
    6969                    nic(asizec{:})=nonlinear_inequality_constraint;
    7070                    clear asizec
    71                    
     71
    7272                    if ischar(varargin{1})
    7373                        varargin{1}=cellstr(varargin{1});
     
    189189        end
    190190    end
    191    
     191
    192192    methods (Static)
    193193        function [rdesc]=dakota_write(fidi,dresp,rdesc)
  • issm/trunk/src/m/classes/qmu/normal_uncertain.m

    r9548 r13975  
    3737        upper     = Inf;
    3838    end
    39    
     39
    4040    methods
    4141        function [nuv]=normal_uncertain(varargin)
     
    6969                    nuv(asizec{:})=normal_uncertain;
    7070                    clear asizec
    71                    
     71
    7272                    if ischar(varargin{1})
    7373                        varargin{1}=cellstr(varargin{1});
     
    193193        end
    194194    end
    195    
     195
    196196    methods (Static)
    197197        function []=dakota_write(fidi,dvar)
  • issm/trunk/src/m/classes/qmu/objective_function.m

    r9548 r13975  
    3535        weight    = 1.;
    3636    end
    37    
     37
    3838    methods
    3939        function [of]=objective_function(varargin)
     
    5454                        of(asizec{:})=objective_function;
    5555                        clear asizec
    56                    
     56
    5757                        if ischar(varargin{1})
    5858                            varargin{1}=cellstr(varargin{1});
     
    169169        end
    170170    end
    171    
     171
    172172    methods (Static)
    173173        function [rdesc]=dakota_write(fidi,dresp,rdesc)
  • issm/trunk/src/m/classes/qmu/response_function.m

    r9548 r13975  
    3737        grell     =[];
    3838    end
    39    
     39
    4040    methods
    4141        function [rf]=response_function(varargin)
     
    5656                        rf(asizec{:})=response_function;
    5757                        clear asizec
    58                    
     58
    5959                        if ischar(varargin{1})
    6060                            varargin{1}=cellstr(varargin{1});
     
    166166        end
    167167    end
    168    
     168
    169169    methods (Static)
    170170        function [rdesc]=dakota_write(fidi,dresp,rdesc)
     
    178178            [rdesc]=rlist_write(fidi,'response_functions','response_function',rf,rdesc);
    179179        end
    180        
     180
    181181        function []=dakota_rlev_write(fidi,dresp,params)
    182182
  • issm/trunk/src/m/classes/qmu/uniform_uncertain.m

    r9548 r13975  
    3232        upper     = Inf;
    3333    end
    34    
     34
    3535    methods
    3636        function [uuv]=uniform_uncertain(varargin)
     
    6464                    uuv(asizec{:})=uniform_uncertain;
    6565                    clear asizec
    66                    
     66
    6767                    if ischar(varargin{1})
    6868                        varargin{1}=cellstr(varargin{1});
     
    152152        end
    153153    end
    154    
     154
    155155    methods (Static)
    156156        function []=dakota_write(fidi,dvar)
  • issm/trunk/src/m/classes/rifts.m

    r13395 r13975  
    3838                                        md = checkmessage(md,['model should be processed for rifts (run meshprocessrifts)!']);
    3939                                end
    40                                 md = checkfield(md,'rifts.riftstruct.fill','values',[WaterEnum() AirEnum() IceEnum() MelangeEnum()]);
     40                                for i=1:numrifts,
     41                                        md = checkfield(md,sprintf('rifts.riftstruct(%d).fill',i),'values',[WaterEnum() AirEnum() IceEnum() MelangeEnum()]);
     42                                end
    4143                        else
    4244                                if ~isnans(obj.riftstruct),
    43                                         md = checkmessage(md,['riftstruct shoud be NaN since numrifts is 0!']);
     45                                        md = checkmessage(md,['riftstruct should be NaN since numrifts is 0!']);
    4446                                end
    4547                        end
  • issm/trunk/src/m/classes/rifts.py

    r13395 r13975  
    1818        def __init__(self):
    1919                # {{{ Properties
    20                 self.riftstruct     = float('NaN')
    21                 self.riftproperties = float('NaN')
     20                self.riftstruct     = []
     21                self.riftproperties = []
    2222
    2323                #set defaults
     
    5353                                #We have segments with rift markers, but no rift structure!
    5454                                md.checkmessage("model should be processed for rifts (run meshprocessrifts)!")
    55                         md = checkfield(md,'rifts.riftstruct.fill','values',[WaterEnum(),AirEnum(),IceEnum(),MelangeEnum()])
     55                        for i,rift in enumerate(self.riftstruct):
     56                                md = checkfield(md,"rifts.riftstruct[%d]['fill']" % i,'values',[WaterEnum(),AirEnum(),IceEnum(),MelangeEnum()])
    5657                else:
    57                         if numpy.any(numpy.logical_not(isnans(self.riftstruct))):
    58                                 md.checkmessage("riftstruct shoud be NaN since numrifts is 0!")
     58                        if self.riftstruct and numpy.any(numpy.logical_not(isnans(self.riftstruct))):
     59                                md.checkmessage("riftstruct should be NaN since numrifts is 0!")
    5960
    6061                return md
     
    7071
    7172                numpairs=0
    72                 for i in xrange(0,numrifts):
    73                         numpairs+=numpy.size(self.riftstruct[i].penaltypairs,0)
     73                for rift in self.riftstruct:
     74                        numpairs+=numpy.size(rift['penaltypairs'],axis=0)
    7475
    7576                # 2 for nodes + 2 for elements+ 2 for  normals + 1 for length + 1 for fill + 1 for friction + 1 for fraction + 1 for fractionincrement + 1 for state.
    7677                data=numpy.zeros((numpairs,12))
    7778                count=0
    78                 for i in xrange(0,numrifts):
    79                         numpairsforthisrift=numpy.size(self.riftstruct[i]['penaltypairs'],0)
    80                         data[count:count+numpairsforthisrift-1,0:6]=self.riftstruct[i]['penaltypairs']
    81                         data[count:count+numpairsforthisrift-1,7]=self.riftstruct[i]['fill']
    82                         data[count:count+numpairsforthisrift-1,8]=self.riftstruct[i]['friction']
    83                         data[count:count+numpairsforthisrift-1,9]=self.riftstruct[i]['fraction']
    84                         data[count:count+numpairsforthisrift-1,10]=self.riftstruct[i]['fractionincrement']
    85                         data[count:count+numpairsforthisrift-1,11]=self.riftstruct[i]['state']
     79                for rift in self.riftstruct:
     80                        numpairsforthisrift=numpy.size(rift['penaltypairs'],0)
     81                        data[count:count+numpairsforthisrift,0:7]=rift['penaltypairs']
     82                        data[count:count+numpairsforthisrift,7]=rift['fill']
     83                        data[count:count+numpairsforthisrift,8]=rift['friction']
     84                        data[count:count+numpairsforthisrift,9]=rift['fraction']
     85                        data[count:count+numpairsforthisrift,10]=rift['fractionincrement']
     86                        data[count:count+numpairsforthisrift,11]=rift['state'].reshape(-1)
    8687                        count+=numpairsforthisrift
    8788
  • issm/trunk/src/m/classes/solver.m

    r13395 r13975  
    9898                                         else
    9999                                                 %option with value. value can be string or scalar
    100                                                  if isscalar(optionvalue),
     100                                                 if isnumeric(optionvalue),
    101101                                                         fprintf(fid,'-%s %g\n',optionname,optionvalue);
    102102                                                 elseif ischar(optionvalue),
  • issm/trunk/src/m/classes/surfaceforcings.m

    r13395 r13975  
    1212                isdelta18o = 0;
    1313                hc = NaN;
     14                href = NaN;
     15                smbref = NaN;
    1416                smb_pos_max = NaN;
    1517                smb_pos_min = NaN;
     
    3537                end % }}}
    3638                function obj = setdefaultparameters(obj) % {{{
    37                  
     39
    3840                  %pdd method not used in default mode
    3941                  obj.ispdd=0;
     
    6062                                elseif(obj.issmbgradients)
    6163                                        md = checkfield(md,'surfaceforcings.hc','forcing',1,'NaN',1);
     64                                        md = checkfield(md,'surfaceforcings.href','forcing',1,'NaN',1);
     65                                        md = checkfield(md,'surfaceforcings.smbref','forcing',1,'NaN',1);
    6266                                        md = checkfield(md,'surfaceforcings.smb_pos_max','forcing',1,'NaN',1);
    6367                                        md = checkfield(md,'surfaceforcings.smb_pos_min','forcing',1,'NaN',1);
     
    8993                        fielddisplay(obj,'issmbgradients','is smb gradients method activated (0 or 1, default is 0)');
    9094                        fielddisplay(obj,'hc',' elevation of intersection between accumulation and ablation regime required if smb gradients is activated');
     95                        fielddisplay(obj,'href',' reference elevation from which deviation is used to calculate SMB adjustment in smb gradients method');
     96                        fielddisplay(obj,'smbref',' reference smb from which deviation is calculated in smb gradients method');
    9197                        fielddisplay(obj,'smb_pos_max',' maximum value of positive smb required if smb gradients is activated');
    9298                        fielddisplay(obj,'smb_pos_min',' minimum value of positive smb required if smb gradients is activated');
     
    117123                        if obj.issmbgradients,
    118124                                WriteData(fid,'object',obj,'fieldname','hc','format','DoubleMat','mattype',1);
     125                                WriteData(fid,'object',obj,'fieldname','href','format','DoubleMat','mattype',1);
     126                                WriteData(fid,'object',obj,'fieldname','smbref','format','DoubleMat','mattype',1);
    119127                                WriteData(fid,'object',obj,'fieldname','smb_pos_max','format','DoubleMat','mattype',1);
    120128                                WriteData(fid,'object',obj,'fieldname','smb_pos_min','format','DoubleMat','mattype',1);
  • issm/trunk/src/m/classes/surfaceforcings.py

    r13395 r13975  
    2222                self.isdelta18o = 0
    2323                self.hc = float('NaN')
     24                self.href = float('NaN')
     25                self.smbref = float('NaN')
    2426                self.smb_pos_max = float('NaN')
    2527                self.smb_pos_min = float('NaN')
     
    5658                string="%s\n%s"%(string,fielddisplay(self,'issmbgradients','is smb gradients method activated (0 or 1, default is 0)'))
    5759                string="%s\n%s"%(string,fielddisplay(self,'hc',' elevation of intersection between accumulation and ablation regime required if smb gradients is activated'))
     60                string="%s\n%s"%(string,fielddisplay(self,'href',' reference elevation from which deviation is used to calculate SMB adjustment in smb gradients method'))
     61                string="%s\n%s"%(string,fielddisplay(self,'smbref',' reference smb from which deviation is calculated in smb gradients method'))
    5862                string="%s\n%s"%(string,fielddisplay(self,'smb_pos_max',' maximum value of positive smb required if smb gradients is activated'))
    5963                string="%s\n%s"%(string,fielddisplay(self,'smb_pos_min',' minimum value of positive smb required if smb gradients is activated'))
     
    9498                        elif self.issmbgradients:
    9599                                md = checkfield(md,'surfaceforcings.hc','forcing',1,'NaN',1)
     100                                md = checkfield(md,'surfaceforcings.href','forcing',1,'NaN',1)
     101                                md = checkfield(md,'surfaceforcings.smbref','forcing',1,'NaN',1)
    96102                                md = checkfield(md,'surfaceforcings.smb_pos_max','forcing',1,'NaN',1)
    97103                                md = checkfield(md,'surfaceforcings.smb_pos_min','forcing',1,'NaN',1)
     
    130136                if self.issmbgradients:
    131137                        WriteData(fid,'object',self,'fieldname','hc','format','DoubleMat','mattype',1)
     138                        WriteData(fid,'object',self,'fieldname','href','format','DoubleMat','mattype',1)
     139                        WriteData(fid,'object',self,'fieldname','smbref','format','DoubleMat','mattype',1)
    132140                        WriteData(fid,'object',self,'fieldname','smb_pos_max','format','DoubleMat','mattype',1)
    133141                        WriteData(fid,'object',self,'fieldname','smb_pos_min','format','DoubleMat','mattype',1)
  • issm/trunk/src/m/classes/thermal.m

    r13395 r13975  
    4747                        md = checkfield(md,'thermal.stabilization','numel',[1],'values',[0 1 2]);
    4848                        md = checkfield(md,'thermal.spctemperature','forcing',1);
    49                         if (ismember(EnthalpyAnalysisEnum(),analyses) & md.thermal.isenthalpy & md.mesh.dimension==3),
    50                                 md = checkfield(md,'thermal.spctemperature','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*(md.geometry.surface-md.mesh.z),'message','spctemperature should be below the adjusted melting point');
     49                        if (ismember(EnthalpyAnalysisEnum(),analyses) & (md.thermal.isenthalpy | solution==EnthalpySolutionEnum()) & md.mesh.dimension==3),
     50                                pos=find(md.thermal.spctemperature(1:md.mesh.numberofvertices,:)~=NaN);
     51                                replicate=repmat(md.geometry.surface-md.mesh.z,1,size(md.thermal.spctemperature,2));
     52                                md = checkfield(md,'thermal.spctemperature(find(md.thermal.spctemperature(1:md.mesh.numberofvertices,:)~=NaN))','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*replicate(pos),'message','spctemperature should be below the adjusted melting point');
    5153                                md = checkfield(md,'thermal.isenthalpy','numel',[1],'values',[0 1]);
    5254                        end
  • issm/trunk/src/m/classes/thermal.py

    r13395 r13975  
    11#module imports
     2import numpy
    23from fielddisplay import fielddisplay
    34from EnumDefinitions import *
     
    6970                md = checkfield(md,'thermal.stabilization','numel',[1],'values',[0,1,2])
    7071                md = checkfield(md,'thermal.spctemperature','forcing',1)
    71                 if EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy and md.mesh.dimension==3:
    72                         md = checkfield(md,'thermal.spctemperature','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*(md.geometry.surface-md.mesh.z),'message',"spctemperature should be below the adjusted melting point")
     72                if EnthalpyAnalysisEnum() in analyses and (md.thermal.isenthalpy or solution==EnthalpySolutionEnum()) and md.mesh.dimension==3:
     73                        pos=numpy.nonzero(numpy.logical_not(numpy.isnan(md.thermal.spctemperature[0:md.mesh.numberofvertices])))
     74                        replicate=numpy.tile(md.geometry.surface-md.mesh.z,(1,numpy.size(md.thermal.spctemperature,axis=1)))
     75                        md = checkfield(md,'thermal.spctemperature[numpy.nonzero(numpy.logical_not(numpy.isnan(md.thermal.spctemperature[0:md.mesh.numberofvertices,:])))]','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*replicate[pos],'message',"spctemperature should be below the adjusted melting point")
    7376                        md = checkfield(md,'thermal.isenthalpy','numel',[1],'values',[0,1])
    7477
  • issm/trunk/src/m/classes/verbose.m

    r13395 r13975  
    99%      control     : control method
    1010%      qmu         : sensitivity analysis
     11%      autodiff    : AD analysis
    1112%
    1213%   Usage:
     
    2324                % {{{
    2425                %BEGINFIELDS
    25                 mprocessor  = false;
    26                 module      = false;
    27                 solution    = false;
    28                 solver      = false;
    29                 convergence = false;
    30                 control     = false;
    31                 qmu         = false;
     26                mprocessor=false;
     27                module=false;
     28                solution=false;
     29                solver=false;
     30                convergence=false;
     31                control=false;
     32                qmu=false;
     33                autodiff=false;
    3234                %ENDFIELDS
    3335                % }}}
     
    8385                if (verbose.control), binary=bitor(binary,32); end
    8486                if (verbose.qmu), binary=bitor(binary,64); end
     87                if (verbose.autodiff), binary=bitor(binary,128); end
    8588                %ENDVERB2BIN
    8689
     
    9093
    9194                %BEGINBIN2VERB
    92                 verbose.mprocessor =logical(bitand(binary, 1));
    93                 verbose.module     =logical(bitand(binary, 2));
    94                 verbose.solution   =logical(bitand(binary, 4));
    95                 verbose.solver     =logical(bitand(binary, 8));
    96                 verbose.convergence=logical(bitand(binary,16));
    97                 verbose.control    =logical(bitand(binary,32));
    98                 verbose.qmu        =logical(bitand(binary,64));
     95                if bitand(binary,1), verbose.mprocessor=true; else verbose.mprocessor=false; end
     96                if bitand(binary,2), verbose.module=true; else verbose.module=false; end
     97                if bitand(binary,4), verbose.solution=true; else verbose.solution=false; end
     98                if bitand(binary,8), verbose.solver=true; else verbose.solver=false; end
     99                if bitand(binary,16), verbose.convergence=true; else verbose.convergence=false; end
     100                if bitand(binary,32), verbose.control=true; else verbose.control=false; end
     101                if bitand(binary,64), verbose.qmu=true; else verbose.qmu=false; end
     102                if bitand(binary,128), verbose.autodiff=true; else verbose.autodiff=false; end
    99103                %ENDBIN2VERB
    100104
     
    105109                end % }}}
    106110                function disp(verbose) % {{{
    107                        
     111
    108112                %BEGINDISP
    109113                disp(sprintf('class ''%s''  = ',class(verbose)));
     
    115119                disp(sprintf('   %15s : %s','control',mat2str(verbose.control)));
    116120                disp(sprintf('   %15s : %s','qmu',mat2str(verbose.qmu)));
     121                disp(sprintf('   %15s : %s','autodiff',mat2str(verbose.autodiff)));
    117122                %ENDDISP
    118123
  • issm/trunk/src/m/classes/verbose.py

    r13395 r13975  
    1616              control     : control method
    1717              qmu         : sensitivity analysis
     18              autodiff    : AD analysis
    1819
    1920           Usage:
     
    3637                self.control     = False
    3738                self.qmu         = False
     39                self.autodiff    = False
    3840                #ENDFIELDS
    3941
     
    6163                        #Cast to logicals
    6264                        listproperties=vars(self)
    63                         for [fieldname,fieldvalue] in listproperties.iteritems():
     65                        for fieldname,fieldvalue in listproperties.iteritems():
    6466                                if isinstance(fieldvalue,bool) or isinstance(fieldvalue,(int,long,float)):
    6567                                        setattr(self,fieldname,bool(fieldvalue))
    6668                                else:
    6769                                        raise TypeError("verbose supported field values are logicals only (True or False)")
     70        # }}}
     71
     72        def __repr__(self):    # {{{
     73                       
     74                #BEGINDISP
     75                s ="class '%s'  = \n" % type(self)
     76                s+="   %15s : %s\n" % ('mprocessor',self.mprocessor)
     77                s+="   %15s : %s\n" % ('module',self.module)
     78                s+="   %15s : %s\n" % ('solution',self.solution)
     79                s+="   %15s : %s\n" % ('solver',self.solver)
     80                s+="   %15s : %s\n" % ('convergence',self.convergence)
     81                s+="   %15s : %s\n" % ('control',self.control)
     82                s+="   %15s : %s\n" % ('qmu',self.qmu)
     83                s+="   %15s : %s\n" % ('autodiff',self.autodiff)
     84                #ENDDISP
     85
     86                return s
    6887        # }}}
    6988
     
    86105                if self.qmu:
    87106                        binary=binary | 64
     107                if self.autodiff:
     108                        binary=binary | 128
    88109                #ENDVERB2BIN
    89110
     
    94115
    95116                #BEGINBIN2VERB
    96                 self.mprocessor =bool(binary &  1)
    97                 self.module     =bool(binary &  2)
    98                 self.solution   =bool(binary &  4)
    99                 self.solver     =bool(binary &  8)
    100                 self.convergence=bool(binary & 16)
    101                 self.control    =bool(binary & 32)
    102                 self.qmu        =bool(binary & 64)
     117                self.mprocessor =bool(binary &   1)
     118                self.module     =bool(binary &   2)
     119                self.solution   =bool(binary &   4)
     120                self.solver     =bool(binary &   8)
     121                self.convergence=bool(binary &  16)
     122                self.control    =bool(binary &  32)
     123                self.qmu        =bool(binary &  64)
     124                self.autodiff   =bool(binary & 128)
    103125                #ENDBIN2VERB
    104126        # }}}
     
    108130        # }}}
    109131
    110         def __repr__(self):    # {{{
    111                        
    112                 #BEGINDISP
    113                 s ="class '%s'  = \n" % type(self)
    114                 s+="   %15s : %s\n" % ('mprocessor',self.mprocessor)
    115                 s+="   %15s : %s\n" % ('module',self.module)
    116                 s+="   %15s : %s\n" % ('solution',self.solution)
    117                 s+="   %15s : %s\n" % ('solver',self.solver)
    118                 s+="   %15s : %s\n" % ('convergence',self.convergence)
    119                 s+="   %15s : %s\n" % ('control',self.control)
    120                 s+="   %15s : %s\n" % ('qmu',self.qmu)
    121                 #ENDDISP
    122 
    123                 return s
     132        def marshall(self,fid):    # {{{
     133                WriteData(fid,'data',self.VerboseToBinary(),'enum',VerboseEnum(),'format','Integer')
    124134        # }}}
    125135
    126         def marshall(self,fid):    # {{{
    127                         WriteData(fid,'data',self.VerboseToBinary(),'enum',VerboseEnum(),'format','Integer')
    128         # }}}
    129 
  • issm/trunk/src/m/consistency/ismodelselfconsistent.m

    r13395 r13975  
    2828
    2929        %Check consistency of the object
    30         if verLessThan('matlab', '7.6')
    31                 md=checkconsistency(md.(field),md,solution,analyses);
    32         else
    33                 md=md.(field).checkconsistency(md,solution,analyses);
    34         end
     30        md=checkconsistency(md.(field),md,solution,analyses);
    3531end
    3632
     
    4642%   Usage:
    4743%      [analyses, numanalyses]=AnalysisConfiguration(solutiontype);
    48 
    49 
    5044
    5145switch solutiontype,
  • issm/trunk/src/m/contrib/bamg/YamsCall.m

    r13395 r13975  
    5353fprintf(fid,'%i %i %i %i\n',[md.mesh.elements zeros(md.mesh.numberofelements,1)]');
    5454numberofelements1=md.mesh.numberofelements;
    55        
     55
    5656%Deal with rifts
    5757if ~isnan(md.rifts.riftstruct),
    58        
     58
    5959        %we have the list of triangles that make up the rift. keep those triangles around during refinement.
    6060        triangles=[];
  • issm/trunk/src/m/contrib/bamg/meshread.m

    r13395 r13975  
    1 function Struct=meshread(filename);
     1function Struct=meshread(filename)
    22
    33%some checks
  • issm/trunk/src/m/contrib/bamg/yams.m

    r13395 r13975  
    1 function md=yams(md,varargin);
     1function md=yams(md,varargin)
    22%MESHYAMS - Build model of Antarctica by refining according to observed velocity error estimator
    33%
     
    102102
    103103end
    104        
     104
    105105disp(['Final mesh, number of elements: ' num2str(md.mesh.numberofelements)]);
    106106
  • issm/trunk/src/m/contrib/gslib/gamv.m

    r13395 r13975  
    1 function output = gamv(x,y,data,varargin);
     1function output = gamv(x,y,data,varargin)
    22%GAMV - use gslib for Kriging
    33%
  • issm/trunk/src/m/contrib/gslib/gslib.m

    r13395 r13975  
    1 function output = gslib(x,y,data,varargin);
     1function output = gslib(x,y,data,varargin)
    22%GSLIB - use gslib for Kriging
    33%
  • issm/trunk/src/m/contrib/gslib/pkriging.m

    r13395 r13975  
    1 function [B E]=pkriging(x,y,observations,x_interp,y_interp,varargin);
     1function [B E]=pkriging(x,y,observations,x_interp,y_interp,varargin)
    22%PKRIGING - parallel Kriging
    33%
  • issm/trunk/src/m/contrib/gslib/varmap.m

    r13395 r13975  
    1 function output = varmap(x,y,data,varargin);
     1function output = varmap(x,y,data,varargin)
    22%VARMAP - use gslib for Kriging
    33%
  • issm/trunk/src/m/contrib/hack/tres.m

    r13395 r13975  
    2222                md.initialization.pressure=md.results.DiagnosticSolution.Pressure;
    2323        end
    24         if md.rifts.numrifts,
     24        if ~isempty(md.rifts.riftstruct),
    2525                if isfield(md.results.DiagnosticSolution,'riftproperties'),
    2626                        md.rifts.riftproperties=md.results.DiagnosticSolution.riftproperties;
    27                 end
    28         end
    29         if md.inversion.iscontrol==1,
    30                 for control_parameters=md.inversion.control_parameters
    31                         %Will need to be updated... good luck ;)
    32                         md.(EnumToModelField(control_parameters))=md.results.DiagnosticSolution.(EnumToString(control_parameters));
    3327                end
    3428        end
  • issm/trunk/src/m/contrib/massbalance/outflow.m

    r13395 r13975  
    1 function flag=outflow(md);
     1function flag=outflow(md)
    22%OUTFLOW - flag nodes on outflux boundary
    33%
  • issm/trunk/src/m/contrib/uci/expremovestraightsegments.m

    r13395 r13975  
    1111for i=1:length(a),
    1212        contour=a(i);
    13        
     13
    1414        s=sqrt(contour.x.^2+contour.y.^2);
    1515        d=diff(s);
    16        
     16
    1717        pos=find(abs(d)>cutoff);
    1818        pos=[0;pos;length(contour.x)];
  • issm/trunk/src/m/enum/EnumDefinitions.py

    r13395 r13975  
    1919        return StringToEnum('AutodiffIsautodiff')[0]
    2020
    21 def AutodiffDependentsEnum():
    22         """
    23         AUTODIFFDEPENDENTSENUM - Enum of AutodiffDependents
    24 
    25            Usage:
    26               macro=AutodiffDependentsEnum()
    27         """
    28 
    29         return StringToEnum('AutodiffDependents')[0]
    30 
    3121def AutodiffNumDependentsEnum():
    3222        """
     
    3929        return StringToEnum('AutodiffNumDependents')[0]
    4030
    41 def AutodiffIndependentsEnum():
    42         """
    43         AUTODIFFINDEPENDENTSENUM - Enum of AutodiffIndependents
    44 
    45            Usage:
    46               macro=AutodiffIndependentsEnum()
    47         """
    48 
    49         return StringToEnum('AutodiffIndependents')[0]
     31def AutodiffNumDependentObjectsEnum():
     32        """
     33        AUTODIFFNUMDEPENDENTOBJECTSENUM - Enum of AutodiffNumDependentObjects
     34
     35           Usage:
     36              macro=AutodiffNumDependentObjectsEnum()
     37        """
     38
     39        return StringToEnum('AutodiffNumDependentObjects')[0]
     40
     41def AutodiffDependentObjectNamesEnum():
     42        """
     43        AUTODIFFDEPENDENTOBJECTNAMESENUM - Enum of AutodiffDependentObjectNames
     44
     45           Usage:
     46              macro=AutodiffDependentObjectNamesEnum()
     47        """
     48
     49        return StringToEnum('AutodiffDependentObjectNames')[0]
     50
     51def AutodiffDependentObjectTypesEnum():
     52        """
     53        AUTODIFFDEPENDENTOBJECTTYPESENUM - Enum of AutodiffDependentObjectTypes
     54
     55           Usage:
     56              macro=AutodiffDependentObjectTypesEnum()
     57        """
     58
     59        return StringToEnum('AutodiffDependentObjectTypes')[0]
     60
     61def AutodiffDependentObjectIndicesEnum():
     62        """
     63        AUTODIFFDEPENDENTOBJECTINDICESENUM - Enum of AutodiffDependentObjectIndices
     64
     65           Usage:
     66              macro=AutodiffDependentObjectIndicesEnum()
     67        """
     68
     69        return StringToEnum('AutodiffDependentObjectIndices')[0]
     70
     71def AutodiffDependentObjectsEnum():
     72        """
     73        AUTODIFFDEPENDENTOBJECTSENUM - Enum of AutodiffDependentObjects
     74
     75           Usage:
     76              macro=AutodiffDependentObjectsEnum()
     77        """
     78
     79        return StringToEnum('AutodiffDependentObjects')[0]
    5080
    5181def AutodiffNumIndependentsEnum():
     
    5989        return StringToEnum('AutodiffNumIndependents')[0]
    6090
     91def AutodiffNumIndependentObjectsEnum():
     92        """
     93        AUTODIFFNUMINDEPENDENTOBJECTSENUM - Enum of AutodiffNumIndependentObjects
     94
     95           Usage:
     96              macro=AutodiffNumIndependentObjectsEnum()
     97        """
     98
     99        return StringToEnum('AutodiffNumIndependentObjects')[0]
     100
     101def AutodiffIndependentObjectNamesEnum():
     102        """
     103        AUTODIFFINDEPENDENTOBJECTNAMESENUM - Enum of AutodiffIndependentObjectNames
     104
     105           Usage:
     106              macro=AutodiffIndependentObjectNamesEnum()
     107        """
     108
     109        return StringToEnum('AutodiffIndependentObjectNames')[0]
     110
     111def AutodiffIndependentObjectTypesEnum():
     112        """
     113        AUTODIFFINDEPENDENTOBJECTTYPESENUM - Enum of AutodiffIndependentObjectTypes
     114
     115           Usage:
     116              macro=AutodiffIndependentObjectTypesEnum()
     117        """
     118
     119        return StringToEnum('AutodiffIndependentObjectTypes')[0]
     120
     121def AutodiffIndependentObjectsEnum():
     122        """
     123        AUTODIFFINDEPENDENTOBJECTSENUM - Enum of AutodiffIndependentObjects
     124
     125           Usage:
     126              macro=AutodiffIndependentObjectsEnum()
     127        """
     128
     129        return StringToEnum('AutodiffIndependentObjects')[0]
     130
    61131def AutodiffJacobianEnum():
    62132        """
     
    79149        return StringToEnum('AutodiffXp')[0]
    80150
    81 def AutodiffFosForwardOutputEnum():
    82         """
    83         AUTODIFFFOSFORWARDOUTPUTENUM - Enum of AutodiffFosForwardOutput
    84 
    85            Usage:
    86               macro=AutodiffFosForwardOutputEnum()
    87         """
    88 
    89         return StringToEnum('AutodiffFosForwardOutput')[0]
     151def AutodiffDriverEnum():
     152        """
     153        AUTODIFFDRIVERENUM - Enum of AutodiffDriver
     154
     155           Usage:
     156              macro=AutodiffDriverEnum()
     157        """
     158
     159        return StringToEnum('AutodiffDriver')[0]
     160
     161def AutodiffFosForwardIndexEnum():
     162        """
     163        AUTODIFFFOSFORWARDINDEXENUM - Enum of AutodiffFosForwardIndex
     164
     165           Usage:
     166              macro=AutodiffFosForwardIndexEnum()
     167        """
     168
     169        return StringToEnum('AutodiffFosForwardIndex')[0]
     170
     171def AutodiffFovForwardIndicesEnum():
     172        """
     173        AUTODIFFFOVFORWARDINDICESENUM - Enum of AutodiffFovForwardIndices
     174
     175           Usage:
     176              macro=AutodiffFovForwardIndicesEnum()
     177        """
     178
     179        return StringToEnum('AutodiffFovForwardIndices')[0]
     180
     181def AutodiffFosReverseIndexEnum():
     182        """
     183        AUTODIFFFOSREVERSEINDEXENUM - Enum of AutodiffFosReverseIndex
     184
     185           Usage:
     186              macro=AutodiffFosReverseIndexEnum()
     187        """
     188
     189        return StringToEnum('AutodiffFosReverseIndex')[0]
     190
     191def AutodiffMassFluxSegmentsPresentEnum():
     192        """
     193        AUTODIFFMASSFLUXSEGMENTSPRESENTENUM - Enum of AutodiffMassFluxSegmentsPresent
     194
     195           Usage:
     196              macro=AutodiffMassFluxSegmentsPresentEnum()
     197        """
     198
     199        return StringToEnum('AutodiffMassFluxSegmentsPresent')[0]
     200
     201def AutodiffKeepEnum():
     202        """
     203        AUTODIFFKEEPENUM - Enum of AutodiffKeep
     204
     205           Usage:
     206              macro=AutodiffKeepEnum()
     207        """
     208
     209        return StringToEnum('AutodiffKeep')[0]
    90210
    91211def BalancethicknessSpcthicknessEnum():
     
    199319        return StringToEnum('ConstantsYts')[0]
    200320
     321def DependentObjectEnum():
     322        """
     323        DEPENDENTOBJECTENUM - Enum of DependentObject
     324
     325           Usage:
     326              macro=DependentObjectEnum()
     327        """
     328
     329        return StringToEnum('DependentObject')[0]
     330
    201331def DiagnosticAbstolEnum():
    202332        """
     
    589719        return StringToEnum('HydrologyStabilization')[0]
    590720
     721def IndependentObjectEnum():
     722        """
     723        INDEPENDENTOBJECTENUM - Enum of IndependentObject
     724
     725           Usage:
     726              macro=IndependentObjectEnum()
     727        """
     728
     729        return StringToEnum('IndependentObject')[0]
     730
    591731def InversionControlParametersEnum():
    592732        """
     
    13191459        return StringToEnum('PrognosticVertexPairing')[0]
    13201460
     1461def PrognosticNumRequestedOutputsEnum():
     1462        """
     1463        PROGNOSTICNUMREQUESTEDOUTPUTSENUM - Enum of PrognosticNumRequestedOutputs
     1464
     1465           Usage:
     1466              macro=PrognosticNumRequestedOutputsEnum()
     1467        """
     1468
     1469        return StringToEnum('PrognosticNumRequestedOutputs')[0]
     1470
     1471def PrognosticRequestedOutputsEnum():
     1472        """
     1473        PROGNOSTICREQUESTEDOUTPUTSENUM - Enum of PrognosticRequestedOutputs
     1474
     1475           Usage:
     1476              macro=PrognosticRequestedOutputsEnum()
     1477        """
     1478
     1479        return StringToEnum('PrognosticRequestedOutputs')[0]
     1480
    13211481def QmuIsdakotaEnum():
    13221482        """
     
    13291489        return StringToEnum('QmuIsdakota')[0]
    13301490
    1331 def QmuMassFluxSegmentsEnum():
    1332         """
    1333         QMUMASSFLUXSEGMENTSENUM - Enum of QmuMassFluxSegments
    1334 
    1335            Usage:
    1336               macro=QmuMassFluxSegmentsEnum()
    1337         """
    1338 
    1339         return StringToEnum('QmuMassFluxSegments')[0]
     1491def MassFluxSegmentsEnum():
     1492        """
     1493        MASSFLUXSEGMENTSENUM - Enum of MassFluxSegments
     1494
     1495           Usage:
     1496              macro=MassFluxSegmentsEnum()
     1497        """
     1498
     1499        return StringToEnum('MassFluxSegments')[0]
     1500
     1501def MassFluxSegmentsPresentEnum():
     1502        """
     1503        MASSFLUXSEGMENTSPRESENTENUM - Enum of MassFluxSegmentsPresent
     1504
     1505           Usage:
     1506              macro=MassFluxSegmentsPresentEnum()
     1507        """
     1508
     1509        return StringToEnum('MassFluxSegmentsPresent')[0]
     1510
     1511def QmuMassFluxSegmentsPresentEnum():
     1512        """
     1513        QMUMASSFLUXSEGMENTSPRESENTENUM - Enum of QmuMassFluxSegmentsPresent
     1514
     1515           Usage:
     1516              macro=QmuMassFluxSegmentsPresentEnum()
     1517        """
     1518
     1519        return StringToEnum('QmuMassFluxSegmentsPresent')[0]
    13401520
    13411521def QmuNumberofpartitionsEnum():
     
    16791859        return StringToEnum('SurfaceforcingsHc')[0]
    16801860
     1861def SurfaceforcingsHrefEnum():
     1862        """
     1863        SURFACEFORCINGSHREFENUM - Enum of SurfaceforcingsHref
     1864
     1865           Usage:
     1866              macro=SurfaceforcingsHrefEnum()
     1867        """
     1868
     1869        return StringToEnum('SurfaceforcingsHref')[0]
     1870
     1871def SurfaceforcingsSmbrefEnum():
     1872        """
     1873        SURFACEFORCINGSSMBREFENUM - Enum of SurfaceforcingsSmbref
     1874
     1875           Usage:
     1876              macro=SurfaceforcingsSmbrefEnum()
     1877        """
     1878
     1879        return StringToEnum('SurfaceforcingsSmbref')[0]
     1880
    16811881def SurfaceforcingsSmbPosMaxEnum():
    16821882        """
     
    25392739        return StringToEnum('DoubleInput')[0]
    25402740
     2741def DataSetParamEnum():
     2742        """
     2743        DATASETPARAMENUM - Enum of DataSetParam
     2744
     2745           Usage:
     2746              macro=DataSetParamEnum()
     2747        """
     2748
     2749        return StringToEnum('DataSetParam')[0]
     2750
    25412751def DoubleMatArrayParamEnum():
    25422752        """
     
    28293039        return StringToEnum('PentaP1Input')[0]
    28303040
     3041def ProfilerEnum():
     3042        """
     3043        PROFILERENUM - Enum of Profiler
     3044
     3045           Usage:
     3046              macro=ProfilerEnum()
     3047        """
     3048
     3049        return StringToEnum('Profiler')[0]
     3050
    28313051def MatrixParamEnum():
    28323052        """
     
    45094729        return StringToEnum('OutputFilePointer')[0]
    45104730
     4731def OutputFileNameEnum():
     4732        """
     4733        OUTPUTFILENAMEENUM - Enum of OutputFileName
     4734
     4735           Usage:
     4736              macro=OutputFileNameEnum()
     4737        """
     4738
     4739        return StringToEnum('OutputFileName')[0]
     4740
     4741def LockFileNameEnum():
     4742        """
     4743        LOCKFILENAMEENUM - Enum of LockFileName
     4744
     4745           Usage:
     4746              macro=LockFileNameEnum()
     4747        """
     4748
     4749        return StringToEnum('LockFileName')[0]
     4750
    45114751def PetscOptionsAnalysesEnum():
    45124752        """
     
    47574997        """
    47584998
    4759         return 474
    4760 
     4999        return 498
     5000
  • issm/trunk/src/m/enum/MaximumNumberOfEnums.m

    r13395 r13975  
    99%      macro=MaximumNumberOfEnums()
    1010
    11 macro=474;
     11macro=498;
  • issm/trunk/src/m/enum/OutputfilenameEnum.m

    r8926 r13975  
    1 function macro=OutputfilenameEnum()
    2 %OUTPUTFILENAMEENUM - Enum of Outputfilename
     1function macro=OutputFileNameEnum()
     2%OUTPUTFILENAMEENUM - Enum of OutputFileName
    33%
    44%   WARNING: DO NOT MODIFY THIS FILE
     
    77%
    88%   Usage:
    9 %      macro=OutputfilenameEnum()
     9%      macro=OutputFileNameEnum()
    1010
    11 macro=StringToEnum('Outputfilename');
     11macro=StringToEnum('OutputFileName');
  • issm/trunk/src/m/exp/expcoarsen.m

    r13395 r13975  
    1 function expcoarsen(newfile,oldfile,resolution);
     1function expcoarsen(newfile,oldfile,resolution)
    22%EXPCOARSEN - coarsen an exp contour
    33%
  • issm/trunk/src/m/exp/expcontract.m

    r13395 r13975  
    66%
    77%   See also EXPMASTER, EXPDOC
    8 
    98
    109contour=expread(oldfile);
  • issm/trunk/src/m/exp/expcreatecontour.m

    r13395 r13975  
    1 function expcreatecontour(filename);
     1function expcreatecontour(filename)
    22%EXPCREATECONTOUR - create a contour from a list of points
    33%
     
    3434%write contour using expwrite
    3535expwrite(a,filename);
    36 
  • issm/trunk/src/m/exp/expcreateprofile.m

    r13395 r13975  
    1 function expcreateprofile(filename);
     1function expcreateprofile(filename)
    22%EXPCREATEPROFILE - create an Argus file from a list of points
    33%
  • issm/trunk/src/m/exp/expexcludeoutliers.m

    r13395 r13975  
    77%
    88%   See also EXPMASTER, EXPDOC
    9 
    109
    1110contour=expread(contourname);
  • issm/trunk/src/m/exp/expflip.m

    r13395 r13975  
    55%
    66%
    7 
    8 
    9 
    10 
    117
    128a=expread(domainname,1);
  • issm/trunk/src/m/exp/expll2xy.m

    r13395 r13975  
    55%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
    66%                               -1 : south latitude (default is mer=0  lat=71)
    7 
    87
    98%Get central_meridian and standard_parallel depending on hemisphere
  • issm/trunk/src/m/exp/expread.m

    r13395 r13975  
    1 function Struct=expread(filename);
     1function Struct=expread(filename)
    22%EXPREAD - read a file exp and build a Structure
    33%
  • issm/trunk/src/m/exp/expswapxy.m

    r13395 r13975  
    66%
    77%   See also EXPMASTER, EXPDOC
    8 
    98
    109contours=expread(filename,1);
  • issm/trunk/src/m/exp/exptool.m

    r13395 r13975  
    308308                        backup{counter,4}=closed;
    309309
    310 
    311310                case 12
    312311
  • issm/trunk/src/m/exp/expwrite.m

    r13395 r13975  
    1 function expwrite(a,filename);
     1function expwrite(a,filename)
    22%EXPWRITE - write an Argus file from a structure given in input
    33%
     
    2020                error('contours x and y coordinates must be of identical size');
    2121        end
    22    
     22
    2323        if isfield(a,'name'),
    2424                if ~isempty(a(n).name),
     
    3030                fprintf(fid,'%s\n','## Name:');
    3131        end
    32    
     32
    3333        fprintf(fid,'%s\n','## Icon:0');
    3434        fprintf(fid,'%s\n','# Points Count Value');
  • issm/trunk/src/m/exp/expxy2ll.m

    r13395 r13975  
    55%      - sgn = Sign of latitude +1 : north latitude (default is mer=45 lat=70)
    66%                               -1 : south latitude (default is mer=0  lat=71)
    7 
    87
    98%Get central_meridian and standard_parallel depending on hemisphere
  • issm/trunk/src/m/exp/manipulation/addcontour.m

    r13395 r13975  
    1 function [A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot,root,options);
     1function [A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot,root,options)
    22%ADDCONTOUR - add a closed contour
    33%
     
    77%   Usage:
    88%      [A,numprofiles,numpoints,closed]=addcontour(A,numprofiles,numpoints,closed,prevplot,root,options)
    9                    
     9
    1010        title('click to add a point to the new profile, RETURN to exit','FontSize',14)
    1111        hold on
     
    1818
    1919                [xi,yi] = ginput(1);
    20                                          
     20
    2121                if ~isempty(xi)
    2222                        x(end+1,1)=xi;
  • issm/trunk/src/m/exp/manipulation/addendprofile.m

    r13395 r13975  
    1 function [A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
     1function [A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
    22%ADDENDPROFILE - add point at the end of a n existing profile
    33%
     
    77%   Usage:
    88%      [A,numprofiles,numpoints,closed]=addendprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
    9                
     9
    1010        %some checks
    1111        if numprofiles==0
  • issm/trunk/src/m/exp/manipulation/addinsideprofile.m

    r13395 r13975  
    1 function [A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
     1function [A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
    22%ADDINSIDEPROFILE - add apoint inside a profile
    33%
     
    77%   Usage:
    88%      [A,numprofiles,numpoints,closed]=addinsideprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
    9                
     9
    1010        %some checks
    1111        if numprofiles==0
  • issm/trunk/src/m/exp/manipulation/addprofile.m

    r13395 r13975  
    1 function [A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
     1function [A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
    22%ADDPROFILE - add a profile
    33%
     
    77%   Usage:
    88%      [A,numprofiles,numpoints,closed]=addprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
    9                    
     9
    1010        title('click to add a point to the new profile, RETURN to exit','FontSize',14)
    1111        hold on
     
    1818
    1919                [xi,yi] = ginput(1);
    20                                          
     20
    2121                if ~isempty(xi)
    2222                        x(end+1,1)=xi;
  • issm/trunk/src/m/exp/manipulation/closeprofile.m

    r13395 r13975  
    1 function [A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
     1function [A,numprofiles,numpoints,closed]=closeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
    22%CLOSEPROFILE - close one or several profile
    33%
     
    1313                return
    1414        end
    15                    
     15
    1616        title('click on the profiles to be closed, RETURN to exit','FontSize',14)
    1717        hold on
     
    3333
    3434                [xi,yi] = ginput(1);
    35                                          
     35
    3636                if ~isempty(xi)
    3737
  • issm/trunk/src/m/exp/manipulation/cutarea.m

    r13395 r13975  
    1 function [A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options);
     1function [A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options)
    22%CUTAREA - cut several point of a profile
    33%
     
    1010%   Usage:
    1111%      [A,numprofiles,numpoints,closed]=cutarea(A,numprofiles,numpoints,closed,prevplot,root,options)
    12                
     12
    1313        hold on
    1414        loop=1;
  • issm/trunk/src/m/exp/manipulation/cutprofile.m

    r13395 r13975  
    1 function [A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
     1function [A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
    22%CUTPROFILE - cut a profile
    33%
     
    77%   Usage:
    88%      [A,numprofiles,numpoints,closed]=cutprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
    9                
     9
    1010        %some checks
    1111        if numprofiles==0
  • issm/trunk/src/m/exp/manipulation/mergeprofiles.m

    r13395 r13975  
    1 function [A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options);
     1function [A,numprofiles,numpoints,closed]=mergeprofiles(A,numprofiles,numpoints,closed,prevplot,root,options)
    22%MERGEPROFILES - merge profiles
    33%
  • issm/trunk/src/m/exp/manipulation/modifyposition.m

    r13395 r13975  
    1 function [A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options);
     1function [A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options)
    22%MODIFYPOSITION - modify the prosition of a point of a profile
    33%
     
    77%   Usage:
    88%      [A,numprofiles,numpoints,closed]=modifyposition(A,numprofiles,numpoints,closed,prevplot,root,options)
    9                
     9
    1010        %some checks
    1111        if numprofiles==0
  • issm/trunk/src/m/exp/manipulation/orientprofile.m

    r13395 r13975  
    1 function [A,numprofiles,numpoints,closed]=orientprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
     1function [A,numprofiles,numpoints,closed]=orientprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
    22%ORIENTPROFILE - cahnge profile orientation
    33%
     
    2121                        return
    2222                end
    23                    
     23
    2424                [xi,yi] = ginput(1);
    25                                          
     25
    2626                if ~isempty(xi)
    2727
  • issm/trunk/src/m/exp/manipulation/removepoints.m

    r13395 r13975  
    1 function [A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options);
     1function [A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options)
    22%REMOVEPOINTS - remove a point from a profile
    33%
     
    77%   Usage:
    88%      [A,numprofiles,numpoints,closed]=removepoints(A,numprofiles,numpoints,closed,prevplot,root,options)
    9                
     9
    1010        %some checks
    1111        if numprofiles==0
  • issm/trunk/src/m/exp/manipulation/removeprofile.m

    r13395 r13975  
    1 function [A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot,root,options);
     1function [A,numprofiles,numpoints,closed]=removeprofile(A,numprofiles,numpoints,closed,prevplot,root,options)
    22%REMOVEPROFILE - delete a profile
    33%
     
    2121                        return
    2222                end
    23                    
     23
    2424                [xi,yi] = ginput(1);
    25                                          
     25
    2626                if ~isempty(xi)
    2727
  • issm/trunk/src/m/exp/manipulation/removeseveralpoints.m

    r13395 r13975  
    1 function [A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options);
     1function [A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options)
    22%REMOVESEVERALPOINTS - remove several point
    33%
     
    77%   Usage:
    88%      [A,numprofiles,numpoints,closed]=removeseveralpoints(A,numprofiles,numpoints,closed,prevplot,root,options)
    9                
     9
    1010        %some checks
    1111        if numprofiles==0
  • issm/trunk/src/m/extrusion/DepthAverage.m

    r13395 r13975  
    1 function  vector_average=DepthAverage(md,vector);
     1function  vector_average=DepthAverage(md,vector)
    22%DEPTHAVERAGE - computes depth average of 3d vector, and return value on 2d mesh.
    33%
  • issm/trunk/src/m/extrusion/project3d.m

    r13395 r13975  
    1 function projected_vector=project3d(md,varargin);
     1function projected_vector=project3d(md,varargin)
    22%PROJECT3D - vertically project a vector from 2d mesh
    33%
  • issm/trunk/src/m/geometry/FlagElements.py

    r13395 r13975  
    22import os
    33#from basinzoom import *
    4 #from ContourToMesh import *
     4from ContourToMesh import *
    55from MatlabFuncs import *
    66
     
    4141                                if len(region)>3 and not strcmp(region[-4:],'.exp'):
    4242                                        raise IOError("Error: File 'region' not found!" % region)
     43                                raise RuntimeError("FlagElements.py calling basinzoom.py is not complete.")
    4344                                xlim,ylim=basinzoom('basin',region)
    4445                                flag_nodes=numpy.logical_and(numpy.logical_and(md.mesh.x<xlim[1],md.mesh.x>xlim[0]),numpy.logical_and(md.mesh.y<ylim[1],md.mesh.y>ylim[0])).astype(float)
     
    4647                        else:
    4748                                #ok, flag elements
    48                                 flag=ContourToMesh(md.mesh.elements[:,0:3],md.mesh.x,md.mesh.y,region,'element',1)
     49                                [flag,dum]=ContourToMesh(md.mesh.elements[:,0:3].copy(),md.mesh.x.reshape(-1,1),md.mesh.y.reshape(-1,1),region,'element',1)
    4950
    5051                if invert:
    5152                        flag=numpy.logical_not(flag)
    5253
    53         elif isinstance(region,numpy.nparray) or isinstance(region,bool):
     54        elif isinstance(region,numpy.ndarray) or isinstance(region,bool):
    5455                if not numpy.size(region,0)==md.mesh.numberofelements:
    5556                        raise TypeError("Flaglist for region must be of same size as number of elements in model.")
  • issm/trunk/src/m/geometry/SegIntersect.m

    r13395 r13975  
    4949        O1C=O2O1'*O1C;
    5050        O1D=O2O1'*O1D;
    51        
     51
    5252        %test if one point is included in the other segment (->bval=1)
    5353        if (O1C-O1A)*(O1D-O1A)<0
  • issm/trunk/src/m/geometry/SegIntersect.py

    r13395 r13975  
    11import numpy
    2 from MatlabFuncs import *
    32
    43def SegIntersect(seg1,seg2):
     
    4847
    4948        #if colinear
    50         if test1*test2==0 and test3*test4==0 and det(numpy.hstack((n1.reshape((-1,1)),n2.reshape(-1,1))))==0:
     49        if test1*test2==0 and test3*test4==0 and numpy.linalg.det(numpy.hstack((n1.reshape((-1,1)),n2.reshape(-1,1))))==0:
    5150
    5251                #projection on the axis O1O2
  • issm/trunk/src/m/interp/PatchToVec.m

    r13395 r13975  
    1 function vec=PatchToVec(Patch);
     1function vec=PatchToVec(Patch)
    22%PATCHTOVEC - converts a patch to a vector by averaging over each vertex
    33%
  • issm/trunk/src/m/interp/SectionValues.m

    r13395 r13975  
    2222        y=infile.y;
    2323end
    24 
    2524
    2625%get the specified resolution
  • issm/trunk/src/m/interp/plugvelocities.m

    r13395 r13975  
    165165        Names.interp='node';
    166166end
     167end
  • issm/trunk/src/m/inversions/parametercontrolB.m

    r13395 r13975  
    3838        md.inversion.nsteps=nsteps;
    3939end
    40 
    4140
    4241%cm_min
  • issm/trunk/src/m/kml/edgeadjacency.m

    r6312 r13975  
    3131        inode1=elem(i,j);
    3232        inode2=elem(i,mod(j,size(elem,2))+1);
    33        
     33
    3434%  loop over the elements containing the first node of the edge to see
    3535%  if they contain the second node of the edge
  • issm/trunk/src/m/kml/exp2kml.m

    r13395 r13975  
    66%
    77
    8 
    98%First, read exp file
    109domain=expread(input);
    11 
    1210
    1311%then transform:
  • issm/trunk/src/m/kml/kml2exp.m

    r13395 r13975  
    66%
    77
    8 
    9 
    10 
    118%First, read polygon kml file.
    129structure=kml_shapefile(input);
    13        
     10
    1411%create exp file:
    1512domain=struct();
  • issm/trunk/src/m/kml/kml_colorstyle.m

    r7460 r13975  
    1818        colormode ='normal';
    1919    end
    20    
     20
    2121    methods
    2222        function [kml]=kml_colorstyle(varargin)
     
    160160
    161161        end
    162        
     162
    163163%  string write the object
    164164
     
    196196
    197197        end
    198        
     198
    199199    end
    200    
     200
    201201end
    202 
  • issm/trunk/src/m/kml/kml_container.m

    r7460 r13975  
    2121    properties
    2222    end
    23    
     23
    2424    methods
    2525        function [kml]=kml_container(varargin)
     
    150150
    151151        end
    152        
     152
    153153%  string write the object
    154154
     
    180180
    181181        end
    182        
     182
    183183%  delete the object
    184184
     
    193193
    194194        end
    195        
     195
    196196    end
    197    
     197
    198198end
    199 
  • issm/trunk/src/m/kml/kml_document.m

    r7460 r13975  
    2323        feature   ={};
    2424    end
    25    
     25
    2626    methods
    2727        function [kml]=kml_document(varargin)
     
    162162
    163163        end
    164        
     164
    165165%  string write the object
    166166
     
    202202
    203203        end
    204        
     204
    205205%  delete the object
    206206
     
    230230
    231231        end
    232        
     232
    233233    end
    234    
     234
    235235end
    236 
  • issm/trunk/src/m/kml/kml_feature.m

    r7460 r13975  
    2828        style     ={};
    2929    end
    30    
     30
    3131    methods
    3232        function [kml]=kml_feature(varargin)
     
    204204
    205205        end
    206        
     206
    207207%  string write the object
    208208
     
    262262
    263263        end
    264        
     264
    265265%  delete the object
    266266
     
    289289
    290290        end
    291        
     291
    292292    end
    293    
     293
    294294end
    295 
  • issm/trunk/src/m/kml/kml_file_swrite.m

    r7418 r13975  
    130130
    131131end
    132 
  • issm/trunk/src/m/kml/kml_file_write.m

    r7270 r13975  
    124124
    125125end
    126 
  • issm/trunk/src/m/kml/kml_folder.m

    r7460 r13975  
    2323        feature   ={};
    2424    end
    25    
     25
    2626    methods
    2727        function [kml]=kml_folder(varargin)
     
    162162
    163163        end
    164        
     164
    165165%  string write the object
    166166
     
    202202
    203203        end
    204        
     204
    205205%  delete the object
    206206
     
    230230
    231231        end
    232        
     232
    233233    end
    234    
     234
    235235end
    236 
  • issm/trunk/src/m/kml/kml_geometry.m

    r7460 r13975  
    1414    properties
    1515    end
    16    
     16
    1717    methods
    1818        function [kml]=kml_geometry(varargin)
     
    143143
    144144        end
    145        
     145
    146146%  string write the object
    147147
     
    173173
    174174        end
    175        
     175
    176176    end
    177    
     177
    178178end
    179 
  • issm/trunk/src/m/kml/kml_linearring.m

    r7461 r13975  
    2222        coords    =zeros(0,3);
    2323    end
    24    
     24
    2525    methods
    2626        function [kml]=kml_linearring(varargin)
     
    165165
    166166        end
    167        
     167
    168168%  string write the object
    169169
     
    203203
    204204        end
    205        
     205
    206206    end
    207    
     207
    208208end
    209 
  • issm/trunk/src/m/kml/kml_linestring.m

    r7460 r13975  
    2222        coords    =zeros(0,3);
    2323    end
    24    
     24
    2525    methods
    2626        function [kml]=kml_linestring(varargin)
     
    165165
    166166        end
    167        
     167
    168168%  string write the object
    169169
     
    203203
    204204        end
    205        
     205
    206206    end
    207    
     207
    208208end
    209 
  • issm/trunk/src/m/kml/kml_linestyle.m

    r7460 r13975  
    1818        width     =1;
    1919    end
    20    
     20
    2121    methods
    2222        function [kml]=kml_linestyle(varargin)
     
    143143
    144144        end
    145        
     145
    146146%  string write the object
    147147
     
    170170
    171171        end
    172        
     172
    173173    end
    174    
     174
    175175end
    176 
  • issm/trunk/src/m/kml/kml_mesh_elem.m

    r9733 r13975  
    100100cmap=colormap;
    101101close(hfig)
    102    
     102
    103103if exist('edata','var')
    104104    if ~exist('cmin','var')
     
    175175
    176176end
    177 
  • issm/trunk/src/m/kml/kml_mesh_write.m

    r9733 r13975  
    193193    cmap=colormap;
    194194    close(hfig)
    195    
     195
    196196    disp(['Writing ' num2str(size(cmap,1)) ' Matlab colors as KML style templates.']);
    197197    for i=1:size(cmap,1)
     
    259259
    260260end
    261 
  • issm/trunk/src/m/kml/kml_multigeometry.m

    r7460 r13975  
    1616        geometry  ={};
    1717    end
    18    
     18
    1919    methods
    2020        function [kml]=kml_multigeometry(varargin)
     
    156156
    157157        end
    158        
     158
    159159%  string write the object
    160160
     
    197197
    198198        end
    199        
     199
    200200%  delete the object
    201201
     
    225225
    226226        end
    227        
     227
    228228    end
    229    
     229
    230230end
    231 
  • issm/trunk/src/m/kml/kml_object.m

    r7460 r13975  
    1515        id        ='';
    1616    end
    17    
     17
    1818    methods
    1919        function [kml]=kml_object(varargin)
     
    144144
    145145        end
    146        
     146
    147147%  string write the object
    148148
     
    174174
    175175        end
    176        
     176
    177177    end
    178    
     178
    179179end
    180 
  • issm/trunk/src/m/kml/kml_part_edges.m

    r12329 r13975  
    101101cmap=colormap;
    102102close(hfig)
    103    
     103
    104104if exist('edata','var')
    105105    if ~exist('cmin','var')
     
    139139    for k=1:md.qmu.numberofpartitions
    140140%        disp(['partition k=' int2str(k)])
    141        
     141
    142142%  for each partition, find all the included elements and determine the
    143143%  perimeter (including those shared by another partition)
     
    154154        [edgeper,elemper,iloop]=edgeperimeter(elemp,nodeconp,edgeadjp);
    155155        iloop(end+1)=size(edgeper,1)+1;
    156        
     156
    157157%  determine the data to be used for the colors (if any)
    158158
     
    170170            end
    171171        end
    172        
     172
    173173%  set up the placemark with multigeometry
    174174
     
    211211            lat=[];
    212212            long=[];
    213            
     213
    214214%  loop over the element edges on the loop of the partition
    215215
     
    241241                    slast=0;
    242242                    j=j+1;
    243                    
     243
    244244%  element not entirely within partition, so figure out boundary
    245245                else
     
    327327                            end
    328328                            nlast=0;
    329                            
     329
    330330%  write out midpoint of first side
    331331                            kline.coords(end+1,:)=[(md.mesh.long(elemp(ielem,slast))...
     
    481481
    482482end
    483 
  • issm/trunk/src/m/kml/kml_part_elems.m

    r9733 r13975  
    101101cmap=colormap;
    102102close(hfig)
    103    
     103
    104104if exist('edata','var')
    105105    if ~exist('cmin','var')
     
    215215
    216216end
    217 
  • issm/trunk/src/m/kml/kml_part_flagedges.m

    r9733 r13975  
    108108
    109109end
    110 
  • issm/trunk/src/m/kml/kml_partitions.m

    r12329 r13975  
    102102cmap=colormap;
    103103close(hfig)
    104    
     104
    105105if exist('edata','var')
    106106    if ~exist('cmin','var')
     
    140140    for k=1:md.qmu.numberofpartitions
    141141%        disp(['partition k=' int2str(k)])
    142        
     142
    143143%  for each partition, find all the included elements and determine the
    144144%  perimeter (including those shared by another partition)
     
    171171            end
    172172        end
    173        
     173
    174174%  set up the placemark with multigeometry
    175175
     
    197197        kmgeom=kml_multigeometry();
    198198        kmgeom.geometry  ={repmat(kml_polygon(),1,length(iloop)-1)};
    199        
     199
    200200%  loop over each loop of the perimeter for the given partition
    201201
     
    213213            lat=[];
    214214            long=[];
    215            
     215
    216216%  loop over the element edges on the loop of the partition
    217217
     
    243243                    slast=0;
    244244                    j=j+1;
    245                    
     245
    246246%  element not entirely within partition, so figure out boundary
    247247                else
     
    329329                            end
    330330                            nlast=0;
    331                            
     331
    332332%  write out midpoint of first side
    333333                            kring.coords(end+1,:)=[(md.mesh.long(elemp(ielem,slast))...
     
    484484
    485485end
    486 
  • issm/trunk/src/m/kml/kml_placemark.m

    r7460 r13975  
    2323        geometry  =kml_geometry.empty();
    2424    end
    25    
     25
    2626    methods
    2727        function [kml]=kml_placemark(varargin)
     
    163163
    164164        end
    165        
     165
    166166%  string write the object
    167167
     
    204204
    205205        end
    206        
     206
    207207%  delete the object
    208208
     
    233233
    234234        end
    235        
     235
    236236    end
    237    
     237
    238238end
    239 
  • issm/trunk/src/m/kml/kml_polygon.m

    r7460 r13975  
    2424        inner     =kml_linearring.empty();
    2525    end
    26    
     26
    2727    methods
    2828        function [kml]=kml_polygon(varargin)
     
    183183
    184184        end
    185        
     185
    186186%  string write the object
    187187
     
    234234
    235235        end
    236        
     236
    237237%  delete the object
    238238
     
    266266
    267267        end
    268        
     268
    269269    end
    270    
     270
    271271end
    272 
  • issm/trunk/src/m/kml/kml_polystyle.m

    r7460 r13975  
    2020        outline   =true;
    2121    end
    22    
     22
    2323    methods
    2424        function [kml]=kml_polystyle(varargin)
     
    148148
    149149        end
    150        
     150
    151151%  string write the object
    152152
     
    176176
    177177        end
    178        
     178
    179179    end
    180    
     180
    181181end
    182 
  • issm/trunk/src/m/kml/kml_style.m

    r7460 r13975  
    3030        list      =[];
    3131    end
    32    
     32
    3333    methods
    3434        function [kml]=kml_style(varargin)
     
    206206
    207207        end
    208        
     208
    209209%  string write the object
    210210
     
    268268
    269269        end
    270        
     270
    271271%  delete the object
    272272
     
    322322
    323323        end
    324        
     324
    325325    end
    326    
     326
    327327end
    328 
  • issm/trunk/src/m/kml/kml_styleselector.m

    r7460 r13975  
    1414    properties
    1515    end
    16    
     16
    1717    methods
    1818        function [kml]=kml_styleselector(varargin)
     
    143143
    144144        end
    145        
     145
    146146%  string write the object
    147147
     
    173173
    174174        end
    175        
     175
    176176    end
    177    
     177
    178178end
    179 
  • issm/trunk/src/m/kml/kml_substyle.m

    r7460 r13975  
    1414    properties
    1515    end
    16    
     16
    1717    methods
    1818        function [kml]=kml_substyle(varargin)
     
    143143
    144144        end
    145        
     145
    146146%  string write the object
    147147
     
    173173
    174174        end
    175        
     175
    176176    end
    177    
     177
    178178end
    179 
  • issm/trunk/src/m/kml/kml_unsh_edges.m

    r12329 r13975  
    114114
    115115end
    116 
  • issm/trunk/src/m/kml/string_buf.m

    r7336 r13975  
    173173
    174174        end
    175        
     175
    176176%  reset the object
    177177
     
    183183
    184184        end
    185        
     185
    186186    end
    187    
     187
    188188end
    189 
  • issm/trunk/src/m/materials/paterson.m

    r13395 r13975  
    22%PATERSON - figure out the rigidity of ice for a given temperature
    33%
    4 %   rigidigty (in s^(1/3)Pa) is the flow law paramter in the flow law sigma=B*e(1/3) (Paterson, p97).
     4%   rigidity (in s^(1/3)Pa) is the flow law paramter in the flow law sigma=B*e(1/3) (Paterson, p97).
    55%   temperature is in Kelvin degrees
    66%
  • issm/trunk/src/m/materials/paterson.py

    r13395 r13975  
    1 from numpy import *
     1import numpy
    22
    33def paterson(temperature):
     4        """
     5        PATERSON - figure out the rigidity of ice for a given temperature
    46
    5     # Local Variables: pos11, pos5, pos10, temperature, pos, T, pos8, pos9, pos6, pos7, pos4, rigidity, pos2, pos3, pos1
    6     # Function calls: length, zeros, argwhere, paterson, error
    7     #PATERSON - figure out the rigidity of ice for a given temperature
    8     #
    9     #   rigidigty (in s^(1/3)Pa) is the flow law paramter in the flow law sigma=B*e(1/3) (Paterson, p97).
    10     #   temperature is in Kelvin degrees
    11     #
    12     #   Usage:
    13     #      rigidity=paterson(temperature)
    14    
    15         pos=argwhere(temperature<0.)
    16         if len(pos):
    17                 print 'input temperature should be in Kelvin (positive)'
    18                 return []
    19    
     7           rigidity (in s^(1/3)Pa) is the flow law paramter in the flow law sigma=B*e(1/3) (Paterson, p97).
     8           temperature is in Kelvin degrees
     9
     10           Usage:
     11              rigidity=paterson(temperature)
     12        """
     13       
     14        if numpy.any(temperature<0.):
     15                raise RuntimeError("input temperature should be in Kelvin (positive)")
     16       
    2017        T = temperature-273.15
     18
    2119        #The routine below is equivalent to:
     20
    2221        # n=3; T=temperature-273;
    2322        # %From paterson,
     
    3130        # rigidity=fittedmodel(temperature);
    3231
    33         rigidity=zeros(len(T))
    34         pos1=argwhere(T<=-45);           rigidity[pos1]=10**8*(-0.000292866376675*(T[pos1]+50)**3+ 0.011672640664130*(T[pos1]+50)**2  -0.325004442485481*(T[pos1]+50)+  6.524779401948101)
    35         pos2=argwhere(logical_and(-45<=T,T<-40));   rigidity[pos2]=10**8*(-0.000292866376675*(T[pos2]+45)**3+ 0.007279645014004*(T[pos2]+45)**2  -0.230243014094813*(T[pos2]+45)+  5.154964909039554)
    36         pos3=argwhere(logical_and(-40<=T,T<-35));   rigidity[pos3]=10**8*(0.000072737147457*(T[pos3]+40)**3+  0.002886649363879*(T[pos3]+40)**2  -0.179411542205399*(T[pos3]+40)+  4.149132666831214)
    37         pos4=argwhere(logical_and(-35<=T,T<-30));   rigidity[pos4]=10**8*(-0.000086144770023*(T[pos4]+35)**3+ 0.003977706575736*(T[pos4]+35)**2  -0.145089762507325*(T[pos4]+35)+  3.333333333333331)
    38         pos5=argwhere(logical_and(-30<=T,T<-25));   rigidity[pos5]=10**8*(-0.000043984685769*(T[pos5]+30)**3+ 0.002685535025386*(T[pos5]+30)**2  -0.111773554501713*(T[pos5]+30)+  2.696559088937191)
    39         pos6=argwhere(logical_and(-25<=T,T<-20));   rigidity[pos6]=10**8*(-0.000029799523463*(T[pos6]+25)**3+ 0.002025764738854*(T[pos6]+25)**2  -0.088217055680511*(T[pos6]+25)+  2.199331606342181)
    40         pos7=argwhere(logical_and(-20<=T,T<-15));   rigidity[pos7]=10**8*(0.000136920904777*(T[pos7]+20)**3+  0.001578771886910*(T[pos7]+20)**2  -0.070194372551690*(T[pos7]+20)+  1.805165505978111)
    41         pos8=argwhere(logical_and(-15<=T,T<-10));   rigidity[pos8]=10**8*(-0.000899763781026*(T[pos8]+15)**3+ 0.003632585458564*(T[pos8]+15)**2  -0.044137585824322*(T[pos8]+15)+  1.510778053489523)
    42         pos9=argwhere(logical_and(-10<=T,T<-5));    rigidity[pos9]=10**8*(0.001676964325070*(T[pos9]+10)**3-  0.009863871256831*(T[pos9]+10)**2  -0.075294014815659*(T[pos9]+10)+  1.268434288203714)
    43         pos10=argwhere(logical_and(-5<=T,T<-2));    rigidity[pos10]=10**8*(-0.003748937622487*(T[pos10]+5)**3+0.015290593619213*(T[pos10]+5)**2  -0.048160403003748*(T[pos10]+5)+  0.854987973338348)
    44         pos11=argwhere(-2<=T);           rigidity[pos11]=10**8*(-0.003748937622488*(T[pos11]+2)**3-0.018449844983174*(T[pos11]+2)**2  -0.057638157095631*(T[pos11]+2)+  0.746900791092860)
     32        rigidity=numpy.zeros((numpy.size(T,axis=0),1))
     33        pos1=numpy.nonzero(T<=-45)
     34        rigidity[pos1]=10**8*(-0.000292866376675*(T[pos1]+50)**3+ 0.011672640664130*(T[pos1]+50)**2  -0.325004442485481*(T[pos1]+50)+  6.524779401948101)
     35        pos2=numpy.nonzero(numpy.logical_and(-45<=T,T<-40))
     36        rigidity[pos2]=10**8*(-0.000292866376675*(T[pos2]+45)**3+ 0.007279645014004*(T[pos2]+45)**2  -0.230243014094813*(T[pos2]+45)+  5.154964909039554)
     37        pos3=numpy.nonzero(numpy.logical_and(-40<=T,T<-35))
     38        rigidity[pos3]=10**8*(0.000072737147457*(T[pos3]+40)**3+  0.002886649363879*(T[pos3]+40)**2  -0.179411542205399*(T[pos3]+40)+  4.149132666831214)
     39        pos4=numpy.nonzero(numpy.logical_and(-35<=T,T<-30))
     40        rigidity[pos4]=10**8*(-0.000086144770023*(T[pos4]+35)**3+ 0.003977706575736*(T[pos4]+35)**2  -0.145089762507325*(T[pos4]+35)+  3.333333333333331)
     41        pos5=numpy.nonzero(numpy.logical_and(-30<=T,T<-25))
     42        rigidity[pos5]=10**8*(-0.000043984685769*(T[pos5]+30)**3+ 0.002685535025386*(T[pos5]+30)**2  -0.111773554501713*(T[pos5]+30)+  2.696559088937191)
     43        pos6=numpy.nonzero(numpy.logical_and(-25<=T,T<-20))
     44        rigidity[pos6]=10**8*(-0.000029799523463*(T[pos6]+25)**3+ 0.002025764738854*(T[pos6]+25)**2  -0.088217055680511*(T[pos6]+25)+  2.199331606342181)
     45        pos7=numpy.nonzero(numpy.logical_and(-20<=T,T<-15))
     46        rigidity[pos7]=10**8*(0.000136920904777*(T[pos7]+20)**3+  0.001578771886910*(T[pos7]+20)**2  -0.070194372551690*(T[pos7]+20)+  1.805165505978111)
     47        pos8=numpy.nonzero(numpy.logical_and(-15<=T,T<-10))
     48        rigidity[pos8]=10**8*(-0.000899763781026*(T[pos8]+15)**3+ 0.003632585458564*(T[pos8]+15)**2  -0.044137585824322*(T[pos8]+15)+  1.510778053489523)
     49        pos9=numpy.nonzero(numpy.logical_and(-10<=T,T<-5))
     50        rigidity[pos9]=10**8*(0.001676964325070*(T[pos9]+10)**3-  0.009863871256831*(T[pos9]+10)**2  -0.075294014815659*(T[pos9]+10)+  1.268434288203714)
     51        pos10=numpy.nonzero(numpy.logical_and(-5<=T,T<-2))
     52        rigidity[pos10]=10**8*(-0.003748937622487*(T[pos10]+5)**3+0.015290593619213*(T[pos10]+5)**2  -0.048160403003748*(T[pos10]+5)+  0.854987973338348)
     53        pos11=numpy.nonzero(-2<=T)
     54        rigidity[pos11]=10**8*(-0.003748937622488*(T[pos11]+2)**3-0.018449844983174*(T[pos11]+2)**2  -0.057638157095631*(T[pos11]+2)+  0.746900791092860)
    4555
    4656        #Now make sure that rigidity is positive
    47         pos=argwhere(rigidity<0);        rigidity[pos]=1**6
     57        pos=numpy.nonzero(rigidity<0)
     58        rigidity[pos]=1**6
    4859
    4960        return rigidity
  • issm/trunk/src/m/mech/basalstress.m

    r13395 r13975  
    66%
    77%   See also: plot_basaldrag
    8 
    98
    109%compute exponents
  • issm/trunk/src/m/mech/cfl_step.m

    r13395 r13975  
    1 function maxtime=cfl_step(md,vx,vy);
     1function maxtime=cfl_step(md,vx,vy)
    22%CFL_STEP - return the maximum time step for the model in years
    33%
  • issm/trunk/src/m/mech/mechanicalproperties.m

    r13395 r13975  
    5151power=(md.materials.rheology_n-1)./(2*md.materials.rheology_n);
    5252second_inv=(ux.^2+vy.^2+((uy+vx).^2)/4+ux.*vy);
     53
    5354%some corrections
    54 location=find(second_inv~=0);
    55 nu(location)=B_bar(location)./(second_inv(location).^power(location));
    5655location=find(second_inv==0 & power~=0);
    5756nu(location)=10^18;     %arbitrary maximum viscosity to apply where there is no effective shear
    58 location=find(second_inv==0 & power==0);
    59 nu(location)=B_bar(location);
     57
     58if isa(md.materials,'matice')
     59        location=find(second_inv~=0);
     60        nu(location)=B_bar(location)./(second_inv(location).^power(location));
     61        location=find(second_inv==0 & power==0);
     62        nu(location)=B_bar(location);
     63elseif isa(md.materials,'matdamageice')
     64        Zinv=md.materials.rheology_Z(index)*summation/3;
     65        location=find(second_inv~=0);
     66        nu(location)=Zinv(location).*B_bar(location)./(second_inv(location).^power(location));
     67        location=find(second_inv==0 & power==0);
     68        nu(location)=Zinv(location).*B_bar(location);
     69        clear Zinv
     70else
     71        error(['class of md.materials (' class(md.materials) ') not recognized or not supported']);
     72end
    6073clear B_bar location second_inv power
    6174
     
    7689        %eigen values and vectors
    7790        [directions,value]=eig(stress);
     91        %sort by absolute value of eigenvalue in descending order
     92        [val,idx]=sort(abs(diag(value)),'descend');
     93        %re-order eigenvalues and associated vectors
     94        value=value(idx,idx);
     95        directions=directions(:,idx);
    7896        valuesstress(i,:)=[value(1,1) value(2,2)];
    7997        directionsstress(i,:)=directions(:)';
    8098        [directions,value]=eig(strain);
     99        %same for strainrate
     100        [val,idx]=sort(abs(diag(value)),'descend');
     101        value=value(idx,idx);
     102        directions=directions(:,idx);
    81103        valuesstrain(i,:)=[value(1,1) value(2,2)];
    82104        directionsstrain(i,:)=directions(:)';
     
    89111stress.yy=tau_yy;
    90112stress.xy=tau_xy;
    91 stress.principalvalue2=valuesstress(:,1);
    92 stress.principalaxis2=directionsstress(:,1:2);
    93 stress.principalvalue1=valuesstress(:,2);
    94 stress.principalaxis1=directionsstress(:,3:4);
     113stress.principalvalue1=valuesstress(:,1);
     114stress.principalaxis1=directionsstress(:,1:2);
     115stress.principalvalue2=valuesstress(:,2);
     116stress.principalaxis2=directionsstress(:,3:4);
    95117stress.effectivevalue=1/sqrt(2)*sqrt(stress.xx.^2+stress.yy.^2+2*stress.xy.^2);
    96118md.results.stress=stress;
     
    100122strainrate.yy=vy;
    101123strainrate.xy=uyvx;
    102 strainrate.principalvalue2=valuesstrain(:,1)*(365.25*24*3600); %strain rate in 1/a instead of 1/s
    103 strainrate.principalaxis2=directionsstrain(:,1:2);
    104 strainrate.principalvalue1=valuesstrain(:,2)*(365.25*24*3600); %strain rate in 1/a instead of 1/s
    105 strainrate.principalaxis1=directionsstrain(:,3:4);
     124strainrate.principalvalue1=valuesstrain(:,1)*(365.25*24*3600); %strain rate in 1/a instead of 1/s
     125strainrate.principalaxis1=directionsstrain(:,1:2);
     126strainrate.principalvalue2=valuesstrain(:,2)*(365.25*24*3600); %strain rate in 1/a instead of 1/s
     127strainrate.principalaxis2=directionsstrain(:,3:4);
    106128strainrate.effectivevalue=1/sqrt(2)*sqrt(strainrate.xx.^2+strainrate.yy.^2+2*strainrate.xy.^2);
    107129md.results.strainrate=strainrate;
     
    111133deviatoricstress.yy=tau_yy;
    112134deviatoricstress.xy=tau_xy;
    113 deviatoricstress.principalvalue2=valuesstress(:,1);
    114 deviatoricstress.principalaxis2=directionsstress(:,1:2);
    115 deviatoricstress.principalvalue1=valuesstress(:,2);
    116 deviatoricstress.principalaxis1=directionsstress(:,3:4);
     135deviatoricstress.principalvalue1=valuesstress(:,1);
     136deviatoricstress.principalaxis1=directionsstress(:,1:2);
     137deviatoricstress.principalvalue2=valuesstress(:,2);
     138deviatoricstress.principalaxis2=directionsstress(:,3:4);
    117139deviatoricstress.effectivevalue=1/sqrt(2)*sqrt(stress.xx.^2+stress.yy.^2+2*stress.xy.^2);
    118140md.results.deviatoricstress=deviatoricstress;
  • issm/trunk/src/m/mesh/ComputeHessian.m

    r13395 r13975  
    2020        error('ComputeHessian error message: the given field size not supported yet');
    2121end
    22 if strcmpi(type,'node') & strcmpi(type,'element'),
     22if ~strcmpi(type,'node') & ~strcmpi(type,'element'),
    2323        error('ComputeHessian error message: only ''node'' or ''element'' type supported yet');
    2424end
     
    2828linesize=3*numberofelements;
    2929
    30 %get areas and  nodal functions coefficients N(x,y)=alpha x + beta y + gamma
     30%get areas and nodal functions coefficients N(x,y)=alpha x + beta y + gamma
    3131[alpha beta]=GetNodalFunctionsCoeff(index,x,y);
    3232areas=GetAreas(index,x,y);
    3333
    34 %comput weights that holds the volume of all the element holding the node i
     34%compute weights that hold the volume of all the element holding the node i
    3535weights=sparse(line,ones(linesize,1),repmat(areas,3,1),numberofnodes,1);
    3636
  • issm/trunk/src/m/mesh/ComputeMetric.m

    r13395 r13975  
    99%      metric=ComputeMetric(hessian,2/9,10^-1,100,10^5,find(md.nodeonwater)
    1010
    11 %first, find the eigen values of eah line of H=[hessian(i,1) hessian(i,2); hessian(i,2) hessian(i,3)]
     11%first, find the eigen values of each line of H=[hessian(i,1) hessian(i,2); hessian(i,2) hessian(i,3)]
    1212a=hessian(:,1); b=hessian(:,2); d=hessian(:,3);
    13 lambda1=0.5*((a+d)+sqrt(4*b.^2+(a-d).^2));
    14 lambda2=0.5*((a+d)-sqrt(4*b.^2+(a-d).^2));
     13lambda1=0.5*((a+d)+sqrt(4.*b.^2+(a-d).^2));
     14lambda2=0.5*((a+d)-sqrt(4.*b.^2+(a-d).^2));
    1515pos1=find(lambda1==0);
    1616pos2=find(lambda2==0);
     
    1818
    1919%Modify the eigen values to control the shape of the elements
    20 lambda1=min(max(abs(lambda1)*scale/epsilon,1/hmax^2),1/hmin^2);
    21 lambda2=min(max(abs(lambda2)*scale/epsilon,1/hmax^2),1/hmin^2);
     20lambda1=min(max(abs(lambda1)*scale/epsilon,1./hmax^2),1./hmin^2);
     21lambda2=min(max(abs(lambda2)*scale/epsilon,1./hmax^2),1./hmin^2);
    2222
    2323%compute eigen vectors
    24 norm1=sqrt(8*b.^2+2*(d-a).^2+2*(d-a).*sqrt((a-d).^2+4*b.^2));
    25 v1x=2*b./norm1;
    26 v1y=((d-a)+sqrt((a-d).^2+4*b.^2))./norm1;
    27 norm2=sqrt(8*b.^2+2*(d-a).^2-2*(d-a).*sqrt((a-d).^2+4*b.^2));
    28 v2x=2*b./norm2;
    29 v2y=((d-a)-sqrt((a-d).^2+4*b.^2))./norm2;
     24norm1=sqrt(8.*b.^2+2.*(d-a).^2+2.*(d-a).*sqrt((a-d).^2+4.*b.^2));
     25v1x=2.*b./norm1;
     26v1y=((d-a)+sqrt((a-d).^2+4.*b.^2))./norm1;
     27norm2=sqrt(8.*b.^2+2.*(d-a).^2-2.*(d-a).*sqrt((a-d).^2+4.*b.^2));
     28v2x=2.*b./norm2;
     29v2y=((d-a)-sqrt((a-d).^2+4.*b.^2))./norm2;
    3030
    31 v1x(pos3)=1; v1y(pos3)=0;
    32 v2x(pos3)=0; v2y(pos3)=1;
     31v1x(pos3)=1.; v1y(pos3)=0.;
     32v2x(pos3)=0.; v2y(pos3)=1.;
    3333
    3434%Compute new metric (for each node M=V*Lambda*V^-1)
     
    3838
    3939%some corrections for 0 eigen values
    40 metric(pos1,:)=repmat([1/hmax^2 0 1/hmax^2],length(pos1),1);
    41 metric(pos2,:)=repmat([1/hmax^2 0 1/hmax^2],length(pos2),1);
     40metric(pos1,:)=repmat([1./hmax^2 0. 1./hmax^2],length(pos1),1);
     41metric(pos2,:)=repmat([1./hmax^2 0. 1./hmax^2],length(pos2),1);
    4242
    4343%take care of water elements
    44 metric(pos,:)=repmat([1/hmax^2 0 1/hmax^2],length(pos),1);
     44metric(pos,:)=repmat([1./hmax^2 0. 1./hmax^2],length(pos),1);
    4545
    4646%take care of NaNs if any (use Matlab eig in a loop)
     
    5454                lambda1=v(1,1);
    5555                lambda2=v(2,2);
    56                 v(1,1)=min(max(abs(lambda1)*scale/epsilon,1/hmax^2),1/hmin^2);
    57                 v(2,2)=min(max(abs(lambda2)*scale/epsilon,1/hmax^2),1/hmin^2);
     56                v(1,1)=min(max(abs(lambda1)*scale/epsilon,1./hmax^2),1./hmin^2);
     57                v(2,2)=min(max(abs(lambda2)*scale/epsilon,1./hmax^2),1./hmin^2);
    5858
    5959                metricTria=u*v*u^(-1);
  • issm/trunk/src/m/mesh/ElementsFromEdge.m

    r13395 r13975  
    1 function edgeelements=ElementsFromEdge(elements,A,B) 
     1function edgeelements=ElementsFromEdge(elements,A,B)
    22%ELEMENTSFROMEDGE: find elements connected to one edge defined by nodes A and B
    33%
    4 % Usage: edgeelements=ElementsFromEdge(elements,A,B)
     4%   Usage: edgeelements=ElementsFromEdge(elements,A,B)
    55%
    6 % Eg:    edgeelements=ElementsFromEdge(md.mesh.elements,tip1,tip2)
     6%   Eg:    edgeelements=ElementsFromEdge(md.mesh.elements,tip1,tip2)
    77%
    88%
    99edgeelements=find(...
    10 (elements(:,1)==A & elements(:,2)==B )| ...
    11 (elements(:,1)==A & elements(:,3)==B )| ...
    12 (elements(:,2)==A & elements(:,3)==B )| ...
    13 (elements(:,2)==A & elements(:,1)==B )| ...
    14 (elements(:,3)==A & elements(:,1)==B )| ...
    15 (elements(:,3)==A & elements(:,2)==B ));
     10        (elements(:,1)==A & elements(:,2)==B )| ...
     11        (elements(:,1)==A & elements(:,3)==B )| ...
     12        (elements(:,2)==A & elements(:,3)==B )| ...
     13        (elements(:,2)==A & elements(:,1)==B )| ...
     14        (elements(:,3)==A & elements(:,1)==B )| ...
     15        (elements(:,3)==A & elements(:,2)==B ));
  • issm/trunk/src/m/mesh/FixMesh.m

    r13395 r13975  
    3232        %now, the index:
    3333        pos=find(index2>orphan); index2(pos)=index2(pos)-1;
    34        
     34
    3535        %look again for orphans on new mesh
    3636        flags=zeros(length(x2),1);flags(index2)=1;
  • issm/trunk/src/m/mesh/MeshQuality.m

    r13395 r13975  
    1 function quality=MeshQuality(md,epsilon,hmin,hmax);
     1function quality=MeshQuality(md,epsilon,hmin,hmax)
    22%MESHQUALITY - compute mesh quality
    33%
  • issm/trunk/src/m/mesh/NodeInElement.m

    r13395 r13975  
    1 function node_in_element=NodeInElement(newx,newy,elements,x,y,nodeconnectivity);
     1function node_in_element=NodeInElement(newx,newy,elements,x,y,nodeconnectivity)
    22% NODEINELEMENT - find for a list of nodes (in newx,newy), which elements in the mesh (elements,x,y) they belong to.
    33%
     
    2525        x0=newx(i);
    2626        y0=newy(i);
    27        
     27
    2828        %first area coordinate
    2929        area_1=(y3y2.*(x0-x3)-x3x2.*(y0-y3))./delta;
     
    3232        %third area coordinate
    3333        area_3=1-area_1-area_2;
    34        
     34
    3535        %get elements for which all area coordinates are positive (meaning (x0,y0) belongs to these elements
    3636        pos=find((area_1>=0-epsilon) & (area_2>=0-epsilon) & (area_3>=0-epsilon));
  • issm/trunk/src/m/mesh/bamg.m

    r13395 r13975  
    5555%initialize the structures required as input of Bamg
    5656bamg_options=struct();
    57 bamg_geometry=bamggeom;
    58 bamg_mesh=bamgmesh;
     57bamg_geometry=bamggeom();
     58bamg_mesh=bamgmesh();
    5959
    6060% Bamg Geometry parameters {{{
     
    6363        %Check that file exists
    6464        domainfile=getfieldvalue(options,'domain');
    65         if ~exist(domainfile,'file') error(['bamg error message: file ' domainfile ' not found ']); end
     65        if ~exist(domainfile,'file') error(['bamg error message: file ' domainfile ' not found']); end
    6666        domain=expread(domainfile);
    6767
     
    7979                        flags=ContourToNodes(domain(i).x,domain(i).y,domain(1),0);
    8080                        if any(~flags),
    81                                 error('bamg error message: All holes should be stricly inside the principal domain');
     81                                error('bamg error message: All holes should be strictly inside the principal domain');
    8282                        end
    8383                end
     
    8686                nods=domain(i).nods-1; %the domain are closed 1=end;
    8787                bamg_geometry.Vertices=[bamg_geometry.Vertices; [domain(i).x(1:nods) domain(i).y(1:nods) ones(nods,1)]];
    88                 bamg_geometry.Edges   =[bamg_geometry.Edges;    [transpose(count+1:count+nods) transpose([count+2:count+nods count+1])  1*ones(nods,1)]];
     88                bamg_geometry.Edges   =[bamg_geometry.Edges;    [transpose(count+1:count+nods) transpose([count+2:count+nods count+1])  1.*ones(nods,1)]];
    8989                if i>1, bamg_geometry.SubDomains=[bamg_geometry.SubDomains; 2 count+1 1 1]; end
    9090
     
    105105                for i=1:length(rift),
    106106
    107                         %detect wether all points of the rift are inside the domain
     107                        %detect whether all points of the rift are inside the domain
    108108                        flags=ContourToNodes(rift(i).x,rift(i).y,domain(1),0);
    109109                        if ~flags,
    110                                 error('one Rift has all his points outside of the domain outline'),
     110                                error('one rift has all its points outside of the domain outline'),
    111111
    112112                        elseif any(~flags),
     
    114114                                disp('Rift tip outside of or on the domain has been detected and is being processed...');
    115115
    116                                 %check that only one point is outsie (for now)
     116                                %check that only one point is outside (for now)
    117117                                if sum(~flags)~=1,
    118118                                        error('bamg error message: only one point outside of the domain is supported yet');
     
    137137                                                %Get position of the two nodes of the edge in domain
    138138                                                i1=j;
    139                                                 i2=mod(j+1,domain(1).nods);
     139                                                i2=j+1;
    140140
    141141                                                %rift is crossing edge [i1 i2] of the domain
     
    152152                                                        disp('moving tip-domain intersection point');
    153153
    154                                                         %Get position of the closest point
     154                                                        %Get position of the closer point
    155155                                                        if tipdis(1)>tipdis(2),
    156156                                                                pos=i2;
     
    160160
    161161                                                        %This point is only in Vertices (number pos).
    162                                                         %OK, no we can add our own rift
     162                                                        %OK, now we can add our own rift
    163163                                                        nods=rift(i).nods-1;
    164164                                                        bamg_geometry.Vertices=[bamg_geometry.Vertices; [rift(i).x(2:end) rift(i).y(2:end) ones(nods,1)]];
    165165                                                        bamg_geometry.Edges=[bamg_geometry.Edges;...
    166166                                                                pos count+1  (1+i);...
    167                                                                 [transpose(count+1:count+nods-1) transpose([count+2:count+nods])  (1+i)*ones(nods-1,1)]];
     167                                                                [transpose(count+1:count+nods-1) transpose(count+2:count+nods)  (1+i)*ones(nods-1,1)]];
    168168                                                        count=count+nods;
    169169
     
    175175                                                        count=count+1;
    176176
    177                                                         %Decompose the crossing edge in 2 subedges
     177                                                        %Decompose the crossing edge into 2 subedges
    178178                                                        pos=find(bamg_geometry.Edges(:,1)==i1 & bamg_geometry.Edges(:,2)==i2);
    179                                                         if isempty(pos) error('bamg error message: a problem occured...'); end
     179                                                        if isempty(pos) error('bamg error message: a problem occurred...'); end
    180180                                                        bamg_geometry.Edges=[bamg_geometry.Edges(1:pos-1,:);...
    181                                                                 bamg_geometry.Edges(pos,1) count                           bamg_geometry.Edges(pos,3);...
    182                                                                 count                      bamg_geometry.Edges(pos,2)   bamg_geometry.Edges(pos,3);...
     181                                                                bamg_geometry.Edges(pos,1) count                      bamg_geometry.Edges(pos,3);...
     182                                                                count                      bamg_geometry.Edges(pos,2) bamg_geometry.Edges(pos,3);...
    183183                                                                bamg_geometry.Edges(pos+1:end,:)];
    184184
    185                                                         %OK, no we can add our own rift
     185                                                        %OK, now we can add our own rift
    186186                                                        nods=rift(i).nods-1;
    187187                                                        bamg_geometry.Vertices=[bamg_geometry.Vertices; [rift(i).x(2:end) rift(i).y(2:end) ones(nods,1)]];
    188188                                                        bamg_geometry.Edges=[bamg_geometry.Edges;...
    189189                                                                count  count+1  2 ;...
    190                                                                 [transpose(count+1:count+nods-1) transpose([count+2:count+nods])  (1+i)*ones(nods-1,1)]];
     190                                                                [transpose(count+1:count+nods-1) transpose(count+2:count+nods)  (1+i)*ones(nods-1,1)]];
    191191                                                        count=count+nods;
    192192
     
    198198                                nods=rift(i).nods-1;
    199199                                bamg_geometry.Vertices=[bamg_geometry.Vertices; [rift(i).x(:) rift(i).y(:) ones(nods+1,1)]];
    200                                 bamg_geometry.Edges=[bamg_geometry.Edges; [transpose(count+1:count+nods) transpose([count+2:count+nods+1])  (1+i)*ones(nods,1)]];
     200                                bamg_geometry.Edges=[bamg_geometry.Edges; [transpose(count+1:count+nods) transpose(count+2:count+nods+1)  (1+i)*ones(nods,1)]];
    201201                                count=count+nods+1;
    202202                        end
     
    210210                track=getfieldvalue(options,'tracks');
    211211                if all(ischar(track)),
    212                         A=expread(track); 
     212                        A=expread(track);
    213213                        track=[A.x A.y];
    214214                else
    215215                        track=double(track); %for some reason, it is of class "single"
    216216                end
    217                 if(size(track,2)==2), track=[track 3*ones(size(track,1),1)]; end
     217                if(size(track,2)==2), track=[track 3.*ones(size(track,1),1)]; end
    218218
    219219                %only keep those inside
     
    224224                nods=size(track,1);
    225225                bamg_geometry.Vertices=[bamg_geometry.Vertices; track];
    226                 bamg_geometry.Edges=[bamg_geometry.Edges; [transpose(count+1:count+nods-1) transpose([count+2:count+nods])  3*ones(nods-1,1)]];
     226                bamg_geometry.Edges=[bamg_geometry.Edges; [transpose(count+1:count+nods-1) transpose(count+2:count+nods)  3.*ones(nods-1,1)]];
    227227
    228228                %update counter
     
    235235                %recover RequiredVertices
    236236                requiredvertices=double(getfieldvalue(options,'RequiredVertices')); %for some reason, it is of class "single"
    237                 if(size(requiredvertices,2)==2), requiredvertices=[requiredvertices 4*ones(size(requiredvertices,1),1)]; end
    238        
     237                if(size(requiredvertices,2)==2), requiredvertices=[requiredvertices 4.*ones(size(requiredvertices,1),1)]; end
     238
    239239                %only keep those inside
    240240                flags=ContourToNodes(requiredvertices(:,1),requiredvertices(:,2),domain(1),0);
     
    276276% Bamg Options {{{
    277277bamg_options.Crack=getfieldvalue(options,'Crack',0);
    278 bamg_options.anisomax=getfieldvalue(options,'anisomax',10^30);
    279 bamg_options.coeff=getfieldvalue(options,'coeff',1);
    280 bamg_options.cutoff=getfieldvalue(options,'cutoff',10^-5);
     278bamg_options.anisomax=getfieldvalue(options,'anisomax',10.^30);
     279bamg_options.coeff=getfieldvalue(options,'coeff',1.);
     280bamg_options.cutoff=getfieldvalue(options,'cutoff',10.^-5);
    281281bamg_options.err=getfieldvalue(options,'err',0.01);
    282282bamg_options.errg=getfieldvalue(options,'errg',0.1);
     
    284284bamg_options.gradation=getfieldvalue(options,'gradation',1.5);
    285285bamg_options.Hessiantype=getfieldvalue(options,'Hessiantype',0);
    286 bamg_options.hmin=getfieldvalue(options,'hmin',10^-100);
    287 bamg_options.hmax=getfieldvalue(options,'hmax',10^100);
     286bamg_options.hmin=getfieldvalue(options,'hmin',10.^-100);
     287bamg_options.hmax=getfieldvalue(options,'hmax',10.^100);
    288288bamg_options.hminVertices=getfieldvalue(options,'hminVertices',[]);
    289289bamg_options.hmaxVertices=getfieldvalue(options,'hmaxVertices',[]);
    290290bamg_options.hVertices=getfieldvalue(options,'hVertices',[]);
    291291bamg_options.KeepVertices=getfieldvalue(options,'KeepVertices',1);
    292 bamg_options.MaxCornerAngle=getfieldvalue(options,'MaxCornerAngle',10);
     292bamg_options.MaxCornerAngle=getfieldvalue(options,'MaxCornerAngle',10.);
    293293bamg_options.maxnbv=getfieldvalue(options,'maxnbv',10^6);
    294 bamg_options.maxsubdiv=getfieldvalue(options,'maxsubdiv',10);
     294bamg_options.maxsubdiv=getfieldvalue(options,'maxsubdiv',10.);
    295295bamg_options.metric=getfieldvalue(options,'metric',[]);
    296296bamg_options.Metrictype=getfieldvalue(options,'Metrictype',0);
     
    298298bamg_options.nbsmooth=getfieldvalue(options,'nbsmooth',3);
    299299bamg_options.omega=getfieldvalue(options,'omega',1.8);
    300 bamg_options.power=getfieldvalue(options,'power',1);
     300bamg_options.power=getfieldvalue(options,'power',1.);
    301301bamg_options.splitcorners=getfieldvalue(options,'splitcorners',1);
    302302bamg_options.geometricalmetric=getfieldvalue(options,'geometricalmetric',0);
     
    334334
    335335%Check for orphan
    336 reshape(md.mesh.elements,3*md.mesh.numberofelements,1);
    337 (~ismember(1:md.mesh.numberofvertices,sort(unique(reshape(md.mesh.elements,3*md.mesh.numberofelements,1)))));
    338336if any(~ismember(1:md.mesh.numberofvertices,sort(unique(reshape(md.mesh.elements,3*md.mesh.numberofelements,1)))))
    339337        error('Output mesh has orphans. Decrease MaxCornerAngle to prevent outside points (ex: 0.01)');
     
    341339end
    342340
    343 function geom=processgeometry(geom,tol,outline); % {{{
     341function geom=processgeometry(geom,tol,outline) % {{{
    344342
    345343%Deal with edges
  • issm/trunk/src/m/mesh/meshconvert.py

    r13395 r13975  
    5252        md.mesh.elementonsurface=numpy.ones(md.mesh.numberofelements)
    5353        md.mesh.vertexonboundary=numpy.zeros(md.mesh.numberofvertices)
    54         md.mesh.vertexonboundary[md.mesh.segments[:,0:1].astype(int)-1]=1
     54        md.mesh.vertexonboundary[md.mesh.segments[:,0:2].astype(int)-1]=1
    5555
    5656        return md
  • issm/trunk/src/m/mesh/planet/mesh_refine_tri4.m

    r13395 r13975  
    2929%
    3030
    31 
    3231% ---this method is not implemented, but the idea here remains...
    3332% This can be done until some minimal distance (D) of the mean
     
    3635% Alternatively, it could be done until some minimum mean
    3736% area of faces is achieved.  As is, it just refines once.
    38 
    3937
    4038% $Revision: 1.1 $ $Date: 2004/11/12 01:32:35 $
     
    8078
    8179for f = 1:Nface,
    82    
     80
    8381    % Get the triangle vertex indices
    8482    NA = FV.faces(f,1);
    8583    NB = FV.faces(f,2);
    8684    NC = FV.faces(f,3);
    87    
     85
    8886    % Get the triangle vertex coordinates
    8987    A = FV.vertices(NA,:);
    9088    B = FV.vertices(NB,:);
    9189    C = FV.vertices(NC,:);
    92    
     90
    9391    % Now find the midpoints between vertices
    9492    a = (A + B) ./ 2;
    9593    b = (B + C) ./ 2;
    9694    c = (C + A) ./ 2;
    97    
     95
    9896    % Find the length of each median
    9997    %A2blen = sqrt ( sum( (A - b).^2, 2 ) );
    10098    %B2clen = sqrt ( sum( (B - c).^2, 2 ) );
    10199    %C2alen = sqrt ( sum( (C - a).^2, 2 ) );
    102    
     100
    103101    % Store the midpoint vertices, while
    104102    % checking if midpoint vertex already exists
     
    106104    [FV, Nb] = mesh_find_vertex(FV,b);
    107105    [FV, Nc] = mesh_find_vertex(FV,c);
    108    
     106
    109107    % Create new faces with orig vertices plus midpoints
    110108    F2(f*4-3,:) = [ NA, Na, Nc ];
     
    112110    F2(f*4-1,:) = [ Nc, Nb, NC ];
    113111    F2(f*4-0,:) = [ Na, Nb, Nc ];
    114    
     112
    115113end
    116114
     
    121119
    122120return
    123 
    124121
    125122%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  • issm/trunk/src/m/mesh/planet/planetmixedmesh.m

    r13395 r13975  
    3333        for j=1:nthetha-1,
    3434                count=(i-1)*(nthetha-1)+j;
    35        
     35
    3636                A=(i-1)*nthetha+j;
    3737                B=(i-1)*nthetha+j+1;
    3838                C=(i)*nthetha+j+1;
    3939                D=(i)*nthetha+j;
    40                
     40
    4141                quads(count,:)=[A B C D];
    4242        end
     
    6464quads=[trias;quads];
    6565
    66 
    6766% now add south pole:
    6867phii=180*conv;
     
    8584quads=[quads;trias];
    8685
    87 
    8886md.mesh.elements=quads;
    8987md.mesh.x=x;
  • issm/trunk/src/m/mesh/planet/sphere_project.m

    r13395 r13975  
    5050% use of arctan functions, which have branches.
    5151
    52 
    5352% Convert Cartesian X,Y,Z to spherical (radians)
    5453theta = atan2( (Y-yo), (X-xo) );
  • issm/trunk/src/m/mesh/planet/sphere_tri.m

    r13395 r13975  
    4343% See also: mesh_refine, sphere_project
    4444%
    45 
    46 
    4745
    4846% $Revision: 1.2 $ $Date: 2005/07/20 23:07:03 $
     
    8078end
    8179
    82 
    8380% -----------------
    8481% define the starting shapes
     
    8885switch shape,
    8986case 'tetra',
    90    
     87
    9188    % Vertices of a tetrahedron
    9289    sqrt_3 = 0.5773502692;
    93    
     90
    9491    tetra.v = [  sqrt_3,  sqrt_3,  sqrt_3 ;   % +X, +Y, +Z  - PPP
    9592                -sqrt_3, -sqrt_3,  sqrt_3 ;   % -X, -Y, +Z  - MMP
    9693                -sqrt_3,  sqrt_3, -sqrt_3 ;   % -X, +Y, -Z  - MPM
    9794                 sqrt_3, -sqrt_3, -sqrt_3 ];  % +X, -Y, -Z  - PMM
    98        
     95
    9996    % Structure describing a tetrahedron
    10097    tetra.f = [ 1, 2, 3;
     
    10299                3, 2, 4;
    103100                4, 1, 3 ];
    104    
     101
    105102    FV.vertices = tetra.v;
    106103    FV.faces    = tetra.f;
    107    
     104
    108105case 'oct',
    109    
     106
    110107    % Six equidistant points lying on the unit sphere
    111108    oct.v = [  1,  0,  0 ;  %  X
     
    115112               0,  0,  1 ;      %  Z
    116113               0,  0, -1 ];     % -Z
    117        
     114
    118115    % Join vertices to create a unit octahedron
    119116    oct.f = [ 1 5 3 ;    %  X  Z  Y  -  First the top half
     
    125122              2 4 6 ;    % -X  Z -Z
    126123              4 1 6 ];   % -Y  Z -Z
    127    
     124
    128125    FV.vertices = oct.v;
    129126    FV.faces    = oct.f;
    130    
     127
    131128case 'ico',
    132    
     129
    133130    % Twelve vertices of icosahedron on unit sphere
    134131    tau = 0.8506508084; % t=(1+sqrt(5))/2, tau=t/sqrt(1+t^2)
    135132    one = 0.5257311121; % one=1/sqrt(1+t^2) , unit sphere
    136    
     133
    137134    ico.v( 1,:) = [  tau,  one,    0 ]; % ZA
    138135    ico.v( 2,:) = [ -tau,  one,    0 ]; % ZB
     
    147144    ico.v(11,:) = [   0 , -tau, -one ]; % XC
    148145    ico.v(12,:) = [   0 ,  tau, -one ]; % XD
    149    
     146
    150147    % Structure for unit icosahedron
    151148    ico.f = [  5,  8,  9 ;
     
    169166               8, 10,  3 ;
    170167               7,  3, 11 ];
    171        
     168
    172169    FV.vertices = ico.v;
    173170    FV.faces    = ico.f;
    174171end
    175 
    176172
    177173% -----------------
    178174% refine the starting shapes with subdivisions
    179175if maxlevel,
    180    
     176
    181177    % Subdivide each starting triangle (maxlevel) times
    182178    for level = 1:maxlevel,
    183        
     179
    184180        % Subdivide each triangle and normalize the new points thus
    185181        % generated to lie on the surface of a sphere radius r.
    186182        FV = mesh_refine_tri4(FV);
    187183        FV.vertices = sphere_project(FV.vertices,r);
    188        
     184
    189185        % An alternative might be to define a min distance
    190186        % between vertices and recurse or use fminsearch
    191        
     187
    192188    end
    193189end
  • issm/trunk/src/m/mesh/rifts/meshaddrifts.m

    r13395 r13975  
    1 function md=meshaddrifts(md,riftname);
     1function md=meshaddrifts(md,riftname)
    22%MESHADDRIFTS - add rifts to a preloaded mesh (typically, an argus mesh)
    33%
     
    1212%        be preserved. There can be as many pairs of closed contour and rift contour as wished.
    1313
    14 
    1514%read rift:
    1615domains=expread(riftname,1);
     
    2019%now loop over rifts:
    2120for rift_i=1:length(rifts),
    22        
     21
    2322        %refine rift to desired resolution:
    2423        contour=contours(rift_i);
    2524        rift=rifts(rift_i);
    26        
     25
    2726        delete('Meshaddrifts.Rift.exp');
    2827        expwrite(rift,'Meshaddrifts.Rift.Coarse.exp');
    2928        expcoarsen('Meshaddrifts.Rift.exp','Meshaddrifts.Rift.Coarse.exp',rift.density);
    3029        delete('Meshaddrifts.Rift.Coarse.exp');
    31        
     30
    3231        %extract model:
    3332        expwrite(contour,'Meshaddrifts.Contour.exp');
    3433        md2=modelextract(md,'Meshaddrifts.Contour.exp');
    35        
     34
    3635        %create domain of md2 model:
    3736        md2.mesh.segments=contourenvelope(md2,'Meshaddrifts.Contour.exp');
     
    4140                domain_index(end+1)=md2.mesh.segments(pos,2);
    4241        end
    43        
     42
    4443        domain.x=md2.mesh.x(domain_index);
    4544        domain.y=md2.mesh.y(domain_index);
     
    4746        domain.density=1;
    4847        expwrite(domain,'Meshaddrifts.Domain.exp');
    49        
     48
    5049        %unloop domain index: used for later.
    5150        domain_index=domain_index(1:end-1);
    52        
     51
    5352        %remesh md2 using new domain outline, and rift profile:
    5453        md2=meshnodensity(md2,'Meshaddrifts.Domain.exp','Meshaddrifts.Rift.exp');
    5554        md2=meshprocessrifts(md2);
    56        
     55
    5756        %plug md2 mesh into md mesh:
    5857        [md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,md.mesh.numberofelements,md.mesh.numberofvertices,elconv,nodeconv,elconv2,nodeconv2]=meshplug(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,...
     
    6160        %update md2 rifts using elconv and nodeconv, and plug them into md:
    6261        md2.rifts=updateriftindexing(md2.rifts,elconv2,nodeconv2);
    63        
     62
    6463        for i=1:md.rifts.numrifts,
    6564                md.rifts.riftstruct(i)=updateriftindexing(md.rifts.riftstruct(i),elconv,nodeconv);
    6665        end
    67        
     66
    6867        if md.rifts.numrifts==0,
    6968                md.rifts.riftstruct=md2.rifts;
     
    7372                md.rifts.numrifts=md.rifts.numrifts+1;
    7473        end
    75        
     74
    7675        md.mesh.segments(:,1:2)=nodeconv(md.mesh.segments(:,1:2));
    7776        md.mesh.segments(:,3)=elconv(md.mesh.segments(:,3));
  • issm/trunk/src/m/mesh/rifts/meshplug.m

    r13395 r13975  
    1 function [elements,x,y,z,numberofelements,numberofnodes,elconv,nodeconv,elconv2,nodeconv2]=meshplug(elements,x,y,z,elements2,x2,y2,z2,extractednodes,extractedelements,domain);
     1function [elements,x,y,z,numberofelements,numberofnodes,elconv,nodeconv,elconv2,nodeconv2]=meshplug(elements,x,y,z,elements2,x2,y2,z2,extractednodes,extractedelements,domain)
    22%MESHPLUG - embed mesh into another one
    33%     See also meshaddrifts
    4 
    54
    65%initialize elconv,nodeconv conversion tables from md mesh to new md mesh
     
    4847end
    4948
    50 
    5149%plug elements
    5250elements=[elements;elements2];
    53 
    5451
    5552%now, increase number of nodes
     
    8784nodeconv(temp_nodeconv)=temp_nodeconvnum;
    8885nodeconv(extractednodes_minusborder)=NaN;
    89 
  • issm/trunk/src/m/mesh/rifts/meshprocessoutsiderifts.m

    r13395 r13975  
    66%
    77
     8%go through rifts, and figure out which ones touch the domain outline
     9for i=1:length(md.rifts.riftstruct),
    810
    9 
    10 %go through rifts, and figure out which ones touch the domain outline
    11 for i=1:md.rifts.numrifts,
    12        
    1311        %first, flag nodes that belong to the domain outline
    1412        flags=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,domainoutline,'node',0);
     
    2018        %we have found outsidetips, tips that touch the domain outline. go through them
    2119        for j=1:length(outsidetips),
    22                
     20
    2321                tip=outsidetips(j);
    2422                %find tip in the segments, take first segment (there should be 2) that holds tip,
     
    4139                elements=[];
    4240
    43                 while  flags(B), %as long as B does not belong to the domain outline, keep looking.
     41                while flags(B), %as long as B does not belong to the domain outline, keep looking.
    4442                        %detect elements on edge A,B:
    4543                        edgeelements=ElementsFromEdge(md.mesh.elements,A,B);
     
    5250                        B=md.mesh.elements(nextelement,find(~ismember(md.mesh.elements(nextelement,:),[A B])));
    5351                end
    54                
     52
    5553                %take the list of elements on one side of the rift that connect to the tip,
    5654                %and duplicate the tip on them, so as to open the rift to the outside.
     
    5957                md.mesh.y=[md.mesh.y;md.mesh.y(tip)];
    6058                md.mesh.numberofvertices=num;
    61                
     59
    6260                %replace tip in elements
    6361                newelements=md.mesh.elements(elements,:);
     
    6967                %deal with segments
    7068                tipsegments=find((md.mesh.segments(:,1)==tip) | (md.mesh.segments(:,2)==tip));
    71                 for  k=1:length(tipsegments),
     69                for k=1:length(tipsegments),
    7270                        segment_index=tipsegments(k);
    7371                        pos=find(md.mesh.segments(segment_index,1:2)~=tip);
     
    8179end
    8280
    83 
    8481%Fill in rest of fields:
    8582md.mesh.numberofelements=length(md.mesh.elements);
     
    8784md.mesh.z=zeros(md.mesh.numberofvertices,1);
    8885md.mesh.vertexonboundary=zeros(length(md.mesh.x),1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2))=1;
    89 md.rifts.numrifts=length(md.rifts.riftstruct);
    9086md.flowequation.element_equation=3*ones(md.mesh.numberofelements,1);
    9187md.mesh.vertexonbed=ones(md.mesh.numberofvertices,1);
  • issm/trunk/src/m/mesh/rifts/rifttipsonmesh.m

    r13395 r13975  
    44
    55%read rifts from outline file
    6 rifts=expread(riftoutline,1);
     6rifts=expread(riftoutline);
    77
    88tips=[];
     
    1313        x_tip=rift.x(1);
    1414        y_tip=rift.y(1);
    15        
     15
    1616        index=find_point(md.mesh.x,md.mesh.y,x_tip,y_tip);
    1717        tips(end+1)=index;
     
    1919        x_tip=rift.x(end);
    2020        y_tip=rift.y(end);
    21        
     21
    2222        index=find_point(md.mesh.x,md.mesh.y,x_tip,y_tip);
    2323        tips(end+1)=index;
    2424
    2525end
    26 
  • issm/trunk/src/m/mesh/rifts/rifttipsrefine.m

    r13395 r13975  
    1 function md=rifttipsrefine(md,filename,resolution,circleradius);
     1function md=rifttipsrefine(md,filename,resolution,circleradius)
    22%RIFTTIPSREFINE - refine mesh near rift tips
    33%
  • issm/trunk/src/m/mesh/roundmesh.m

    r13395 r13975  
    1212
    1313%Get number of points on the circle
    14 pointsonedge=floor((2*pi*radius) / resolution);
     14pointsonedge=floor((2.*pi*radius) / resolution);
    1515
    1616%Calculate the cartesians coordinates of the points
    1717x_list=ones(pointsonedge,1); y_list=ones(pointsonedge,1);
    18 theta=(0:2*pi/pointsonedge:2*pi*(1-1/pointsonedge))';
    19 x_list=radius*x_list.*cos(theta);
    20 y_list=radius*y_list.*sin(theta);
    21 A=struct('x',x_list,'y',y_list,'density',1);
     18theta=(0.:2.*pi/pointsonedge:2.*pi*(1.-1./pointsonedge))';
     19x_list=roundsigfig(radius*x_list.*cos(theta),12);
     20y_list=roundsigfig(radius*y_list.*sin(theta),12);
     21A=struct('x',x_list,'y',y_list,'density',1.);
    2222expwrite(A,'RoundDomainOutline.exp');
    2323
     
    2828%move the closest node to the center
    2929[mini pos]=min(md.mesh.x.^2+md.mesh.y.^2);
    30 md.mesh.x(pos)=0;
    31 md.mesh.y(pos)=0;
     30md.mesh.x(pos)=0.;
     31md.mesh.y(pos)=0.;
    3232
    3333%delete domain
    3434delete('RoundDomainOutline.exp')
     35end
     36
     37function x=roundsigfig(x,n)
     38
     39digits=ceil(log10(abs(x)));
     40x=x./10.^digits;
     41x=round(x.*10.^n)./10.^n;
     42x=x.*10.^digits;
     43
     44pos=find(isnan(x));
     45x(pos)=0.;
     46
     47end
     48
  • issm/trunk/src/m/mesh/triangle.py

    r13395 r13975  
    1 from numpy import *
    2 import TriMesh as tm
    3 import NodeConnectivity as nc
    4 import ElementConnectivity as ec
     1import numpy
     2from TriMesh import *
     3from NodeConnectivity import *
     4from ElementConnectivity import *
     5from MatlabFuncs import *
    56
    6 def triangle(md, domainname, resolution,riftname=''):
    7         #TRIANGLE - create model mesh using the triangle package
    8         #
    9         #   This routine creates a model mesh using TriMesh and a domain outline, to within a certain resolution
    10         #   where md is a @model object, domainname is the name of an Argus domain outline file,
    11         #   and resolution is a characteristic length for the mesh (same unit as the domain outline
    12         #   unit). Riftname is an optional argument (Argus domain outline) describing rifts.
    13         #
    14         #   Usage:
    15         #      md=triangle(md,domainname,resolution)
    16         #   or md=triangle(md,domainname, resolution, riftname)
    17         #
    18         #   Examples:
    19         #      md=triangle(md,'DomainOutline.exp',1000);
    20         #      md=triangle(md,'DomainOutline.exp',1000,'Rifts.exp');
     7def triangle(md,domainname,*args):
     8        """
     9        TRIANGLE - create model mesh using the triangle package
    2110
     11           This routine creates a model mesh using TriMesh and a domain outline, to within a certain resolution
     12           where md is a @model object, domainname is the name of an Argus domain outline file,
     13           and resolution is a characteristic length for the mesh (same unit as the domain outline
     14           unit). Riftname is an optional argument (Argus domain outline) describing rifts.
     15
     16           Usage:
     17              md=triangle(md,domainname,resolution)
     18           or md=triangle(md,domainname, resolution, riftname)
     19
     20           Examples:
     21              md=triangle(md,'DomainOutline.exp',1000);
     22              md=triangle(md,'DomainOutline.exp',1000,'Rifts.exp');
     23        """
    2224
    2325        #Figure out a characteristic area. Resolution is a node oriented concept (ex a 1000m  resolution node would
    2426        #be made of 1000*1000 area squares).
    2527
     28        if len(args)==1:
     29                resolution=args[0]
     30                riftname=''
     31        if len(args)==2:
     32                riftname=args[0]
     33                resolution=args[1]
     34
    2635        #Check that mesh was not already run, and warn user:
    27         if md.mesh.numberofelements != 0.:
    28                 choice = input('This model already has a mesh. Are you sure you want to go ahead? (y/n)')
    29                 if choice != 'y':
     36        if md.mesh.numberofelements:
     37                choice = raw_input('This model already has a mesh. Are you sure you want to go ahead? (y/n)')
     38                if not strcmp(choice,'y'):
    3039                        print 'no meshing done ... exiting'
    31                         return []
    32                
    33         area = resolution**2.
     40                        return None
     41
     42        area = resolution**2
    3443
    3544        #Mesh using TriMesh
    36         [md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers]=tm.TriMesh(domainname,riftname,area)
    37 
     45        [md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers]=TriMesh(domainname,riftname,area)
    3846
    3947        #Fill in rest of fields:
    40         md.mesh.numberofelements = len(md.mesh.elements)
    41         md.mesh.numberofvertices = len(md.mesh.x)
    42         md.mesh.z = zeros(md.mesh.numberofvertices)
    43         md.mesh.vertexonboundary = zeros(md.mesh.numberofvertices)
     48        md.mesh.numberofelements = numpy.size(md.mesh.elements,axis=0)
     49        md.mesh.numberofvertices = numpy.size(md.mesh.x)
     50        md.mesh.z = numpy.zeros(md.mesh.numberofvertices)
     51        md.mesh.vertexonboundary = numpy.zeros(md.mesh.numberofvertices)
    4452        md.mesh.vertexonboundary[md.mesh.segments[:,0:2].astype(int)-1] = 1.
    45         md.mesh.vertexonbed = ones(md.mesh.numberofvertices)
    46         md.mesh.vertexonsurface = ones(md.mesh.numberofvertices)
    47         md.mesh.elementonbed = ones(md.mesh.numberofelements)
    48         md.mesh.elementonsurface = ones(md.mesh.numberofelements)
     53        md.mesh.vertexonbed = numpy.ones(md.mesh.numberofvertices)
     54        md.mesh.vertexonsurface = numpy.ones(md.mesh.numberofvertices)
     55        md.mesh.elementonbed = numpy.ones(md.mesh.numberofelements)
     56        md.mesh.elementonsurface = numpy.ones(md.mesh.numberofelements)
    4957
    5058        #Now, build the connectivity tables for this mesh.
    51         [md.mesh.vertexconnectivity]= nc.NodeConnectivity(md.mesh.elements, md.mesh.numberofvertices)
    52         [md.mesh.elementconnectivity] = ec.ElementConnectivity(md.mesh.elements, md.mesh.vertexconnectivity)
    53        
     59        [md.mesh.vertexconnectivity]= NodeConnectivity(md.mesh.elements, md.mesh.numberofvertices)
     60        [md.mesh.elementconnectivity] = ElementConnectivity(md.mesh.elements, md.mesh.vertexconnectivity)
     61
    5462        #type of model
    5563        md.mesh.dimension = 2.
     64
    5665        return md
     66
  • issm/trunk/src/m/miscellaneous/MatlabFuncs.py

    r13395 r13975  
    5353
    5454        else:
    55                 b=numpy.empty_like(a)
    56                 for i,item in enumerate(a.flat):
    57                         b.flat[i]=item in s
     55                if not isinstance(s,numpy.ndarray):
     56                        b=numpy.empty_like(a)
     57                        for i,item in enumerate(a.flat):
     58                                b.flat[i]=item in s
     59                else:
     60                        b=numpy.in1d(a.flat,s.flat).reshape(a.shape)
    5861
    5962        return b
    6063
     64def det(a):
     65        import numpy
     66
     67        if   a.shape==(1,):
     68                return a[0]
     69        elif a.shape==(1,1):
     70                return a[0,0]
     71        elif a.shape==(2,2):
     72                return a[0,0]*a[1,1]-a[0,1]*a[1,0]
     73        else:
     74                raise TypeError("MatlabFunc.det only implemented for shape (2, 2), not for shape %s." % str(a.shape))
     75
     76def sparse(ivec,jvec,svec,m=0,n=0,nzmax=0):
     77        import numpy
     78
     79        if not m:
     80                m=numpy.max(ivec)
     81        if not n:
     82                n=numpy.max(jvec)
     83
     84        a=numpy.zeros((m,n))
     85
     86        for i,j,s in zip(ivec.reshape(-1,order='F'),jvec.reshape(-1,order='F'),svec.reshape(-1,order='F')):
     87                a[i-1,j-1]+=s
     88
     89        return a
     90
  • issm/trunk/src/m/miscellaneous/fielddisplay.m

    r13395 r13975  
    1313end %function
    1414
    15 function parsedisplay(offset,name,field,comment); %{{{
     15function parsedisplay(offset,name,field,comment) %{{{
    1616
    1717        %string
  • issm/trunk/src/m/miscellaneous/fielddisplay.py

    r13395 r13975  
    5050        elif isinstance(field,(list,tuple)):
    5151                string=list_display(offset,name,field,comment)
     52
     53        #None
     54        elif field is None:
     55                string=displayunit(offset,name,"None",comment)
    5256
    5357        else:
     
    128132                        string="%s%-23s: %-15s -- %s" % (offset,name,characterization,comment[0])
    129133                        for commenti in comment:
    130                                 string+="\n%s%-23s  %-15s    %s" % (offset,'','',comment[i])
     134                                string+="\n%s%-23s  %-15s    %s" % (offset,'','',commenti)
    131135                else:
    132136                        raise RuntimeError("fielddisplay error message: format for comment not supported yet")
  • issm/trunk/src/m/miscellaneous/isnans.m

    r13395 r13975  
    55%
    66%  See also : ISNAN
    7 
    87
    98if isstruct(array),
  • issm/trunk/src/m/miscellaneous/issmdoc.m

    r13395 r13975  
    44ISSM_DIR=issmdir();
    55
    6 disp(sprintf('\n%s','  A comprehensive documentation is available on http://issm.jpl.nasa.gov'));
    7 disp(sprintf('\n%s','  Example: how to create a square ice shelf'));
    8 disp(sprintf('%s','        go to ',ISSM_DIR,'/examples/SquareIceshelf'));
    9 disp(sprintf('%s','        md=model;                                %creates a new empty model structure'));
    10 disp(sprintf('%s','        md=triangle(md,''DomainOutline.exp'',50000);   %creates a mesh of the domain outline with a resolution of 50000m'));
    11 disp(sprintf('%s','        md=setmask(md,''all'','''');               %defines the glacier system as an ice shelf (no island)'));
    12 disp(sprintf('%s','        md=parameterize(md,''Square.par'');        %fills all the other fields of the model'));
    13 disp(sprintf('%s','        md=setflowequation(md,''macayeal'',''all''); %defines all elements as MacAyeal''s'));
    14 disp(sprintf('%s','        md=solve(md,DiagnosticSolutionEnum());   %generate the velocity field'));
    15 disp(sprintf('%s','        plotmodel(md,''data'',md.results.DiagnosticSolution.Vel);    %displays the velocity (type plotdoc for plotmodel help)'));
     6disp('  A comprehensive documentation is available on http://issm.jpl.nasa.gov');
     7disp('  Example: how to create a square ice shelf');
     8disp(['       go to ',ISSM_DIR,'/examples/SquareIceShelf']);
     9disp(sprintf('%-63s %s','       md=model;','%creates a new empty model structure'));
     10disp(sprintf('%-63s %s','       md=triangle(md,''DomainOutline.exp'',50000);','%creates a mesh of the domain outline with a resolution of 50000 m'));
     11disp(sprintf('%-63s %s','       md=setmask(md,''all'','''');','%defines the glacier system as an ice shelf (no island)'));
     12disp(sprintf('%-63s %s','       md=parameterize(md,''Square.par'');','%fills all the other fields of the model'));
     13disp(sprintf('%-63s %s','       md=setflowequation(md,''macayeal'',''all'');','%defines all elements as MacAyeal''s SSA'));
     14disp(sprintf('%-63s %s','       md=solve(md,DiagnosticSolutionEnum());','%solve for stress balance'));
     15disp(sprintf('%-63s %s','       plotmodel(md,''data'',md.results.DiagnosticSolution.Vel);','%displays the velocity (type plotdoc for plotmodel help)'));
  • issm/trunk/src/m/miscellaneous/parallelrange.m

    r13395 r13975  
    1212end
    1313
    14 
    1514%There may be some rows left. Distribute evenly.
    1615row_rest=globalsize - numprocs*floor(globalsize/numprocs);
  • issm/trunk/src/m/os/ismpi.m

    r13395 r13975  
    44%   Usage:
    55%       flag=ismpi();
    6 
    76
    87configfile=[issmdir() '/bin/config.h']; %should find it in the install target
  • issm/trunk/src/m/os/ismumps.m

    r13395 r13975  
    44%   Usage:
    55%       flag=ismumps();
    6 
    76
    87configfile=[issmdir() '/bin/config.h']; %should find it in the install target
  • issm/trunk/src/m/os/ispetsc.m

    r13395 r13975  
    44%   Usage:
    55%       flag=ispetsc();
    6 
    76
    87configfile=[issmdir() '/bin/config.h']; %should find it in the install target
  • issm/trunk/src/m/os/issmbbftpin.m

    r13395 r13975  
    3535        end
    3636        command=[command '''  pfe1.nas.nasa.gov'];
    37        
     37
    3838        eval(command);
    3939
     
    4545        end
    4646
    47 
    4847end
  • issm/trunk/src/m/os/issmbbftpout.m

    r13395 r13975  
    1919        end
    2020else
    21        
     21
    2222        %build a string of the type: bbftp -s -u elarour -e 'setnbstream 8; cd /nobackupp10/elarour/Testing/Interactive3/; put Antarctica.tar.gz' pfe1.nas.nasa.gov
    2323        command=['!bbftp -s -V -u ' login ' -e ''setnbstream 8; cd ' path '; ']
     
    2626        end
    2727        command=[command '''  pfe1.nas.nasa.gov'];
    28        
     28
    2929        eval(command);
    3030end
  • issm/trunk/src/m/os/issmscpin.m

    r13395 r13975  
    3131        if ispc(),
    3232                %use the putty project pscp.exe: it should be in the path.
    33                
     33
    3434                %get ISSM_DIR variable
    3535                [status,ISSM_DIR]=system('echo [%ISSM_DIR_WIN%]');
     
    6262                end
    6363
    64 
    6564                if port,
    6665                        eval(['!scp -P ' num2str(port) ' ' login '@localhost:' path '/' string ' ./']);
     
    6867                        eval(['!scp ' login '@' host ':' path '/' string ' ./']);
    6968                end
    70                
     69
    7170                %check scp worked
    7271                for i=1:numel(packages),
  • issm/trunk/src/m/os/issmscpout.m

    r13395 r13975  
    2222        if ispc(),
    2323                %use the putty project pscp.exe: it should be in the path.
    24                
     24
    2525                %get ISSM_DIR variable
    2626                [status,ISSM_DIR]=system('echo [%ISSM_DIR_WIN%]');
     
    4848                end
    4949                string=[string ' '];
    50                
     50
    5151                if port,
    5252                        eval(['!scp -P ' num2str(port) ' ' string ' ' login '@localhost:' path]);
  • issm/trunk/src/m/os/issmssh.m

    r13395 r13975  
    1414        if ispc(),
    1515                %use the putty project plink.exe: it should be in the path.
    16                
     16
    1717                %get ISSM_DIR variable
    1818                [status,ISSM_DIR]=system('echo [%ISSM_DIR_WIN%]');
  • issm/trunk/src/m/os/issmssh.py

    r13395 r13975  
    4040                                subprocess.call('ssh -l %s %s "%s"' % (login,host,command),shell=True)
    4141
     42        # The following code was added to fix:
     43        # "IOError: [Errno 35] Resource temporarily unavailable"
     44        # on the Mac when trying to display md after the solution.
     45        # (from http://code.google.com/p/robotframework/issues/detail?id=995)
     46
     47        # Make FreeBSD use blocking I/O like other platforms
     48        import sys
     49        import fcntl
     50        from os import O_NONBLOCK
     51
     52        fd = sys.stdin.fileno()
     53        flags = fcntl.fcntl(fd, fcntl.F_GETFL)
     54        fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~O_NONBLOCK)
     55
     56        fd = sys.stdout.fileno()
     57        flags = fcntl.fcntl(fd, fcntl.F_GETFL)
     58        fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~O_NONBLOCK)
     59
  • issm/trunk/src/m/os/oshostname.m

    r13395 r13975  
    77
    88if ispc(),
    9         [status,hostname]=system('hostname | sed ''s/-//g''');hostname=hostname(1:end-1);
    10 
     9        [status,hostname]=system('hostname | sed ''s/-//g''');
    1110        if status,
    1211                error('oshostname error message: could not run hostname command on windows os');
    1312        end
    14 
    1513else
    1614        [status,hostname]=system(['hostname -s | sed ''s/-//g''']);
     
    1816                error('oshostname error message: could not run hostname command on *nix os');
    1917        end
    20         hostname=hostname(1:end-1);
    21         hostname=ddewhite(hostname);
     18
    2219end
     20
     21%remove carriage return and blank spaces
     22hostname=hostname(1:end-1);
     23hostname=ddewhite(hostname);
  • issm/trunk/src/m/parameterization/contourenvelope.m

    r13395 r13975  
    2020        if ischar(flags),
    2121                file=flags;
    22                 file=varargin{1};
    2322                if ~exist(file),
    2423                        error(['contourenvelope error message: file ' file ' not found']);
     
    2928                isfile=0;
    3029        else
    31                 error('contourenvelope error message:  second argument should a file or an elements flag');
     30                error('contourenvelope error message:  second argument should be a file or an elements flag');
    3231        end
    3332end
     
    7069        else
    7170                %get flag list of elements and nodes inside the contour
    72                 nodein=zeros(mesh.numberofvertices,1); 
    73                 elemin=zeros(mesh.numberofelements,1); 
    74                
    75                 pos=find(flags); 
     71                nodein=zeros(mesh.numberofvertices,1);
     72                elemin=zeros(mesh.numberofelements,1);
     73
     74                pos=find(flags);
    7675                elemin(pos)=1;
    7776                nodein(mesh.elements(pos,:))=1;
     
    9594pos=find(elementonboundary);
    9695num_segments=length(pos);
    97 segments=zeros(num_segments,3);
     96segments=zeros(num_segments*3,3);
    9897count=1;
    9998
     
    138137        end
    139138end
     139segments=segments(1:count-1,:);
     140
  • issm/trunk/src/m/parameterization/parameterize.m

    r13395 r13975  
    5656end
    5757md.miscellaneous.notes=['Model created by using parameter file: ' parametername ' on: ' datestr(now)];
    58 
  • issm/trunk/src/m/parameterization/setflowequation.py

    r13395 r13975  
    9494                                              numpy.logical_not(numpy.isnan(md.diagnostic.spcvy)).astype(int)+ \
    9595                                              numpy.logical_not(numpy.isnan(md.diagnostic.spcvz)).astype(int)==3, \
    96                                               numpy.logical_and(nodeonpattyn,nodeonstokes)).astype(int)    #find all the nodes on the boundary of the domain without icefront
     96                                              numpy.logical_and(nodeonpattyn,nodeonstokes).reshape(-1,1)).astype(int)    #find all the nodes on the boundary of the domain without icefront
    9797#               fullspcelems=double(sum(fullspcnodes(md.mesh.elements),2)==6);         %find all the nodes on the boundary of the domain without icefront
    9898                fullspcelems=(numpy.sum(fullspcnodes[md.mesh.elements.astype(int)-1],axis=1)==6).astype(int)    #find all the nodes on the boundary of the domain without icefront
    99                 stokesflag[numpy.nonzero(fullspcelems)]=0
     99                stokesflag[numpy.nonzero(fullspcelems.reshape(-1))]=0
    100100                nodeonstokes[md.mesh.elements[numpy.nonzero(stokesflag),:].astype(int)-1]=1
    101101
     
    123123                numnodes2d=md.mesh.numberofvertices2d
    124124                numlayers=md.mesh.numberoflayers
    125                 bordernodes2d=numpy.nonzero(numpy.logical_and(nodeonpattyn[1:numnodes2d],nodeonmacayeal[1:numnodes2d]))    #Nodes connected to two different types of elements
     125                bordernodes2d=numpy.nonzero(numpy.logical_and(nodeonpattyn[0:numnodes2d],nodeonmacayeal[0:numnodes2d]))[0]+1    #Nodes connected to two different types of elements
    126126
    127127                #initialize and fill in penalties structure
     
    129129                        penalties=numpy.zeros((0,2))
    130130                        for     i in xrange(1,numlayers):
    131                                 penalties=numpy.concatenate((penalties,numpy.concatenate((bordernodes2d,bordernodes2d+md.mesh.numberofvertices2d*(i)),axis=1)),axis=0)
     131                                penalties=numpy.vstack((penalties,numpy.hstack((bordernodes2d.reshape(-1,1),bordernodes2d.reshape(-1,1)+md.mesh.numberofvertices2d*(i)))))
    132132                        md.diagnostic.vertex_pairing=penalties
    133133
     
    137137                        nodeonmacayealpattyn[numpy.nonzero(numpy.logical_and(nodeonmacayeal,nodeonpattyn))]=1
    138138                        #Macayeal elements in contact with this layer become MacAyealPattyn elements
    139                         matrixelements=ismember(md.mesh.elements,numpy.nonzero(nodeonmacayealpattyn))
     139                        matrixelements=ismember(md.mesh.elements.astype(int)-1,numpy.nonzero(nodeonmacayealpattyn)[0])
    140140                        commonelements=numpy.sum(matrixelements,axis=1)!=0
    141141                        commonelements[numpy.nonzero(pattynflag)]=0    #only one layer: the elements previously in macayeal
     
    146146
    147147                        #rule out elements that don't touch the 2 boundaries
    148                         pos=numpy.nonzero(macayealpattynflag)
    149                         elist=numpy.zeros(len(pos))
    150                         elist = elist + numpy.any(numpy.sum(nodeonmacayeal[md.mesh.elements[pos,:].astype(int)-1],axis=1),axis=1)
    151                         elist = elist - numpy.any(numpy.sum(nodeonpattyn[md.mesh.elements[pos,:].astype(int)-1]  ,axis=1),axis=1)
    152                         pos1=numpy.nonzero(elist==1)
     148                        pos=numpy.nonzero(macayealpattynflag)[0]
     149                        elist=numpy.zeros(numpy.size(pos),dtype=int)
     150                        elist = elist + numpy.sum(nodeonmacayeal[md.mesh.elements[pos,:].astype(int)-1],axis=1).astype(bool)
     151                        elist = elist - numpy.sum(nodeonpattyn[md.mesh.elements[pos,:].astype(int)-1]  ,axis=1).astype(bool)
     152                        pos1=numpy.nonzero(elist==1)[0]
    153153                        macayealflag[pos[pos1]]=1
    154154                        macayealpattynflag[pos[pos1]]=0
    155                         pos2=numpy.nonzero(elist==-1)
     155                        pos2=numpy.nonzero(elist==-1)[0]
    156156                        pattynflag[pos[pos2]]=1
    157157                        macayealpattynflag[pos[pos2]]=0
     
    169169                        nodeonpattynstokes[numpy.nonzero(numpy.logical_and(nodeonpattyn,nodeonstokes))]=1
    170170                        #Stokes elements in contact with this layer become PattynStokes elements
    171                         matrixelements=ismember(md.mesh.elements,numpy.nonzero(nodeonpattynstokes))
     171                        matrixelements=ismember(md.mesh.elements.astype(int)-1,numpy.nonzero(nodeonpattynstokes)[0])
    172172                        commonelements=numpy.sum(matrixelements,axis=1)!=0
    173173                        commonelements[numpy.nonzero(pattynflag)]=0    #only one layer: the elements previously in macayeal
     
    178178
    179179                        #rule out elements that don't touch the 2 boundaries
    180                         pos=numpy.nonzero(pattynstokesflag)
    181                         elist=numpy.zeros(len(pos))
    182                         elist = elist + numpy.any(numpy.sum(nodeonstokes[md.mesh.elements[pos,:].astype(int)-1],axis=1),axis=1)
    183                         elist = elist - numpy.any(numpy.sum(nodeonpattyn[md.mesh.elements[pos,:].astype(int)-1],axis=1),axis=1)
    184                         pos1=numpy.nonzero(elist==1)
     180                        pos=numpy.nonzero(pattynstokesflag)[0]
     181                        elist=numpy.zeros(numpy.size(pos),dtype=int)
     182                        elist = elist + numpy.sum(nodeonstokes[md.mesh.elements[pos,:].astype(int)-1],axis=1).astype(bool)
     183                        elist = elist - numpy.sum(nodeonpattyn[md.mesh.elements[pos,:].astype(int)-1],axis=1).astype(bool)
     184                        pos1=numpy.nonzero(elist==1)[0]
    185185                        stokesflag[pos[pos1]]=1
    186186                        pattynstokesflag[pos[pos1]]=0
    187                         pos2=numpy.nonzero(elist==-1)
     187                        pos2=numpy.nonzero(elist==-1)[0]
    188188                        pattynflag[pos[pos2]]=1
    189189                        pattynstokesflag[pos[pos2]]=0
     
    201201                        nodeonmacayealstokes[numpy.nonzero(numpy.logical_and(nodeonmacayeal,nodeonstokes))]=1
    202202                        #Stokes elements in contact with this layer become MacAyealStokes elements
    203                         matrixelements=ismember(md.mesh.elements,numpy.nonzero(nodeonmacayealstokes))
     203                        matrixelements=ismember(md.mesh.elements.astype(int)-1,numpy.nonzero(nodeonmacayealstokes)[0])
    204204                        commonelements=numpy.sum(matrixelements,axis=1)!=0
    205205                        commonelements[numpy.nonzero(macayealflag)]=0    #only one layer: the elements previously in macayeal
     
    210210
    211211                        #rule out elements that don't touch the 2 boundaries
    212                         pos=numpy.nonzero(macayealstokesflag)
    213                         elist=numpy.zeros(len(pos))
    214                         elist = elist + numpy.any(numpy.sum(nodeonmacayeal[md.mesh.elements[pos,:].astype(int)-1],axis=1),axis=1)
    215                         elist = elist - numpy.any(numpy.sum(nodeonstokes[md.mesh.elements[pos,:].astype(int)-1]  ,axis=1),axis=1)
    216                         pos1=numpy.nonzero(elist==1)
     212                        pos=numpy.nonzero(macayealstokesflag)[0]
     213                        elist=numpy.zeros(numpy.size(pos),dtype=int)
     214                        elist = elist + numpy.sum(nodeonmacayeal[md.mesh.elements[pos,:].astype(int)-1],axis=1).astype(bool)
     215                        elist = elist - numpy.sum(nodeonstokes[md.mesh.elements[pos,:].astype(int)-1]  ,axis=1).astype(bool)
     216                        pos1=numpy.nonzero(elist==1)[0]
    217217                        macayealflag[pos[pos1]]=1
    218218                        macayealstokesflag[pos[pos1]]=0
    219                         pos2=numpy.nonzero(elist==-1)
     219                        pos2=numpy.nonzero(elist==-1)[0]
    220220                        stokesflag[pos[pos2]]=1
    221221                        macayealstokesflag[pos[pos2]]=0
  • issm/trunk/src/m/parameterization/setmask.py

    r13395 r13975  
    1 from numpy import *
    2 import FlagElements as fe
     1import numpy
     2from FlagElements import *
    33
    44def setmask(md, floatingicename, groundedicename):
    5         #SETMASK - establish boundaries between grounded and floating ice.
    6         #
    7         #   By default, ice is considered grounded. The contour floatingicename defines nodes
    8         #   for which ice is floating. The contour groundedicename defines nodes inside an floatingice,
    9         #   that are grounded (ie: ice rises, islands, etc ...)
    10         #   All input files are in the Argus format (extension .exp).
    11         #
    12         #   Usage:
    13         #      md=setmask(md,floatingicename,groundedicename)
    14         #
    15         #   Examples:
    16         #      md=setmask(md,'all','');
    17         #      md=setmask(md,'Iceshelves.exp','Islands.exp');
     5        """
     6        SETMASK - establish boundaries between grounded and floating ice.
    187
    19         #%Get assigned fields
     8           By default, ice is considered grounded. The contour floatingicename defines nodes
     9           for which ice is floating. The contour groundedicename defines nodes inside an floatingice,
     10           that are grounded (ie: ice rises, islands, etc ...)
     11           All input files are in the Argus format (extension .exp).
     12
     13           Usage:
     14              md=setmask(md,floatingicename,groundedicename)
     15
     16           Examples:
     17              md=setmask(md,'all','');
     18              md=setmask(md,'Iceshelves.exp','Islands.exp');
     19        """
     20
     21        #Get assigned fields
    2022        x = md.mesh.x
    2123        y = md.mesh.y
     
    2325
    2426        #Assign elementonfloatingice, elementongroundedice, vertexongroundedice and vertexonfloatingice. Only change at your own peril! This is synchronized heavily with the GroundingLineMigration module. {{{
    25         elementonfloatingice = fe.FlagElements(md, floatingicename)
    26         elementongroundedice = fe.FlagElements(md, groundedicename)
     27        elementonfloatingice = FlagElements(md, floatingicename)
     28        elementongroundedice = FlagElements(md, groundedicename)
    2729
    2830        #Because groundedice nodes and elements can be included into an floatingice, we need to update. Remember, all the previous
    2931        #arrays come from domain outlines that can intersect one another:
    3032
    31         elementonfloatingice = logical_and(elementonfloatingice,~elementongroundedice)
    32         elementongroundedice = ~elementonfloatingice
     33        elementonfloatingice = numpy.logical_and(elementonfloatingice,numpy.logical_not(elementongroundedice))
     34        elementongroundedice = numpy.logical_not(elementonfloatingice)
    3335
    3436        #the order here is important. we choose vertexongroundedice as default on the grounding line.
    35         vertexonfloatingice = zeros(md.mesh.numberofvertices,'bool')
    36         vertexongroundedice = zeros(md.mesh.numberofvertices,'bool')
    37 
    38         pos=argwhere(elementongroundedice==1)
    39         pos=md.mesh.elements[pos,:]-1
    40         if pos.size:
    41                 vertexongroundedice[pos]=True
    42 
    43         pos=argwhere(~vertexongroundedice)
    44         if pos.size:
    45                 vertexonfloatingice[pos]=True;
    46         #%}}}
     37        vertexonfloatingice = numpy.zeros(md.mesh.numberofvertices,'bool')
     38        vertexongroundedice = numpy.zeros(md.mesh.numberofvertices,'bool')
     39        vertexongroundedice[md.mesh.elements[numpy.nonzero(elementongroundedice),:].astype(int)-1]=True
     40        vertexonfloatingice[numpy.nonzero(numpy.logical_not(vertexongroundedice))]=True
     41        #}}}
    4742
    4843        #Return:
    49         md.mask.elementonfloatingice = double(elementonfloatingice)
    50         md.mask.vertexonfloatingice = double(vertexonfloatingice)
    51         md.mask.elementongroundedice = double(elementongroundedice)
    52         md.mask.vertexongroundedice = double(vertexongroundedice)
    53         md.mask.vertexonwater = zeros(md.mesh.numberofvertices)
    54         md.mask.elementonwater = zeros(md.mesh.numberofelements)
     44        md.mask.elementonfloatingice = elementonfloatingice.astype(float)
     45        md.mask.vertexonfloatingice = vertexonfloatingice.astype(float)
     46        md.mask.elementongroundedice = elementongroundedice.astype(float)
     47        md.mask.vertexongroundedice = vertexongroundedice.astype(float)
     48        md.mask.vertexonwater = numpy.zeros(md.mesh.numberofvertices)
     49        md.mask.elementonwater = numpy.zeros(md.mesh.numberofelements)
     50
    5551        return md
  • issm/trunk/src/m/partition/AreaAverageOntoPartition.m

    r13395 r13975  
    1515        %save 3D model
    1616        md3d=md;
    17        
     17
    1818        md.mesh.elements=md.mesh.elements2d;
    1919        md.mesh.x=md.mesh.x2d;
  • issm/trunk/src/m/partition/adjacency.m

    r13395 r13975  
    1 function md=adjacency(md);
     1function md=adjacency(md)
    22%ADJACENCY -  compute adjacency matrix, list of vertices and list of weights.
    33%
  • issm/trunk/src/m/partition/flagedges.m

    r13395 r13975  
    1 function [xsegments ysegments]=flagedges(elements,x,y,partition);
     1function [xsegments ysegments]=flagedges(elements,x,y,partition)
    22%FLAGEDGES - return pairs of x,y segments, delimiting partitions.
    33%
  • issm/trunk/src/m/partition/partitioner.m

    r13395 r13975  
    5050end
    5151
    52 
    5352if strcmpi(package,'chaco'),
    5453
     
    5756        method(1)=3;    %  global method (3=inertial (geometric))
    5857        method(3)=0;    %  vertex weights (0=off, 1=on)
    59        
     58
    6059        %specify bisection
    6160        method(6)=getfieldvalue(options,'section');%  ndims (1=bisection, 2=quadrisection, 3=octasection)
     
    6867                weights=[];
    6968        end
    70        
     69
    7170        %  partition into nparts
    7271        part=Chaco(md.qmu.adjacency,weights,[],md.mesh.x, md.mesh.y ,md.mesh.z,method,npart,[])'+1; %index partitions from 1 up. like metis.
     
    7978        end
    8079        maptab=Scotch(md.qmu.adjacency,[],weights,[],'cmplt',[npart]);
    81        
     80
    8281        part=maptab(:,2);%index partitions from 1 up. like metis.
    83 
    8482
    8583elseif strcmpi(package,'linear'),
  • issm/trunk/src/m/plot/applyoptions.m

    r13395 r13975  
    66%
    77%   See also: PLOTMODEL, PARSE_OPTIONS
    8                
    98
    109%some defaults
     
    147146        end
    148147        if exist(options,'log'),
    149                 nlab=5;
     148                nlab=length(get(c,'YTick'));
    150149                logvalue=getfieldvalue(options,'log');
    151150
     
    176175        if exist(options,'colorbarYLabel'),
    177176                set(get(c,'Ylabel'),'FontSize',getfieldvalue(options,'colorbarfontsize',fontsize),'String',getfieldvalue(options,'colorbarYLabel'),...
    178                         'Color',getfieldvalue(options,'FontColor','k'),'Interpreter',getfieldvalue(options,'Interpreter','none'));
     177                        'Color',getfieldvalue(options,'FontColor','k'));
    179178        end
    180179        if exist(options,'colorbarwidth'),
     
    215214                        end
    216215                end
    217                 labels = cell(1,size(tick_vals,1));
    218                 for i = 1:size(tick_vals,1)
    219                         labels{i} = sprintf('%-3.4g',round_ice(tick_vals(i),2));
     216                labels = cell(1,numel(tick_vals));
     217                for i = 1:numel(tick_vals)
     218                        labels{i} = num2str(tick_vals(i));
    220219                end
    221220                set(c,'YTickLabel',labels);
     
    226225else
    227226        %do nothing
    228        
    229 end
    230 
     227
     228end
    231229
    232230%area
     
    269267end
    270268
     269%curved arrow
     270if exist(options,'curvedarrow'),
     271        curvedoptions=getfieldvalue(options,'curvedarrow');
     272        curvedarrow(curvedoptions{:});
     273end
     274
    271275%Scale ruler
    272276if exist(options,'scaleruler'),
     
    320324end
    321325
    322 
    323326%position of figure
    324327if exist(options,'figposition'),
    325        
     328
    326329        figposition=getfieldvalue(options,'figposition');
    327330        if ischar(figposition),
     
    430433        data=getfieldvalue(options,'scatter');
    431434        hold on
    432         plot_scatter(data(:,1),data(:,2),getfieldvalue(options,'scattersize',3),data(:,3),options);
     435        plot_scatter(data(:,1),data(:,2),data(:,3),options);
    433436end
    434437
  • issm/trunk/src/m/plot/arrow.m

    r13395 r13975  
    88%            'ratio': default .5 (ratio headarrow/length)
    99%            'widthratio': default is 1/10 of length
    10 
    1110
    1211%recover options
  • issm/trunk/src/m/plot/checkplotoptions.m

    r13395 r13975  
    1 function options=checkplotoptions(md,options);
     1function options=checkplotoptions(md,options)
    22%PARSE_OPTIONS - build a structure that holds all plot options
    33%
     
    5353        end
    5454end
    55        
     55
    5656%text
    5757if exist(options,'text'),
  • issm/trunk/src/m/plot/colormaps/getcolormap.m

    r13395 r13975  
    2121
    2222if strcmpi(map,'Ala'),
    23         map = jet;
     23        map = jet(256);
    2424        map = map(128:end,:);
    2525elseif strcmpi(map,'redblue'),
  • issm/trunk/src/m/plot/colormaps/haxby.m

    r13395 r13975  
    1 function map = haxby(m);
     1function map = haxby(m)
    22%HAXBY - Haxby color map
    33%   HAXBY(M) returns an M-by-3 matrix containing a colormap with Haxby's
  • issm/trunk/src/m/plot/kmlgroundoverlay.m

    r13395 r13975  
    1 function kmlgroundoverlay(md,options);
     1function kmlgroundoverlay(md,options)
    22%KMLGROUNDOVERLAY: create ground overlay image in kml format
    33%
  • issm/trunk/src/m/plot/latlonoverlay.m

    r13395 r13975  
    117117        end
    118118
    119 
    120119        pos=find(x<=xlimits(2) & x>=xlimits(1) & y<=ylimits(2) & y>=ylimits(1));
    121120        if length(pos)<=1, continue; end
  • issm/trunk/src/m/plot/plot_BC.m

    r13395 r13975  
    1 function plot_BC(md,options,width,i,data);
     1function plot_BC(md,options,width,i,data)
    22
    33%plot neuman
  • issm/trunk/src/m/plot/plot_basaldrag.m

    r13395 r13975  
    1 function plot_basaldrag(md,options,width,i,type);
     1function plot_basaldrag(md,options,width,i,type)
    22
    33%PLOT_BASALDRAG - plot basal drag
  • issm/trunk/src/m/plot/plot_boundaries.m

    r13395 r13975  
    1 function plot_boundaries(md,options,width,i);
     1function plot_boundaries(md,options,width,i)
    22%PLOT_BOUNDARIES - plot mesh boundaries
    33%
  • issm/trunk/src/m/plot/plot_contour.m

    r13395 r13975  
    1 function plot_contour(md,datain,options);
     1function plot_contour(md,datain,options)
    22%PLOT_CONTOUR - plot contours of a given field
    33%
  • issm/trunk/src/m/plot/plot_drivingstress.m

    r13395 r13975  
    1 function plot_drivingstress(md,options,width,i);
     1function plot_drivingstress(md,options,width,i)
    22%PLOT_DRIVINGSTRESS - plot driving stress
    33%
  • issm/trunk/src/m/plot/plot_edges.m

    r13395 r13975  
    1 function plot_edges(md,options,width,i,datai);
     1function plot_edges(md,options,width,i,datai)
    22%PLOT_SEGMENTS - plot edges, with different colors according to segment markers.
    33%
  • issm/trunk/src/m/plot/plot_elementnumbering.m

    r13395 r13975  
    1 function plot_elementnumbering(md,options,width,i);
     1function plot_elementnumbering(md,options,width,i)
    22%PLOT_ELEMENTNUMBERING - plot element numbering
    33%
  • issm/trunk/src/m/plot/plot_elementstype.m

    r13395 r13975  
    1 function plot_elementstype(md,options,width,i);
     1function plot_elementstype(md,options,width,i)
    22%PLOT_ELEMENTSTYPE - plot elements type
    33%
  • issm/trunk/src/m/plot/plot_highlightelements.m

    r13395 r13975  
    1 function plot_highlightelements(md,options,width,i);
     1function plot_highlightelements(md,options,width,i)
    22%PLOT_HIGHLIGHTELEMENTS - plot selected elements
    33%
  • issm/trunk/src/m/plot/plot_highlightvertices.m

    r13395 r13975  
    1 function plot_highlightvertices(md,options,width,i);
     1function plot_highlightvertices(md,options,width,i)
    22%PLOT_HIGHLIGHTVERTICES - plot selected vertices
    33%
     
    2121        %Highlight
    2222        pos=getfieldvalue(options,'highlight',[]);
    23         text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
     23        text(x(pos),y(pos),z(pos),num2str(pos(:)),...
    2424                'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
    2525else
     
    3434        %Highlight
    3535        pos=getfieldvalue(options,'highlight',[]);
    36         text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
     36        text(x(pos),y(pos),z(pos),num2str(pos(:)),...
    3737                'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
    3838end
  • issm/trunk/src/m/plot/plot_icefront.m

    r13395 r13975  
    1 function plot_icefront(md,options,width,i,data);
     1function plot_icefront(md,options,width,i,data)
    22%PLOT_ICEFRONT - plot segment on neumann BC
    33%
  • issm/trunk/src/m/plot/plot_importancefactors.m

    r13395 r13975  
    1 function plot_importancefactors(md,options,width,ii);
     1function plot_importancefactors(md,options,width,ii)
    22%PLOT_IMPORTANCEFACTORS - plot importance factors
    33%
  • issm/trunk/src/m/plot/plot_manager.m

    r13395 r13975  
    1 function plot_manager(md,options,subplotwidth,nlines,ncols,i);
     1function plot_manager(md,options,subplotwidth,nlines,ncols,i)
    22%PLOT__MANAGER - distribute the plots, called by plotmodel
    33%
     
    3333                        plot_highlightelements(md,options,subplotwidth,i);
    3434                        return;
    35                
     35
    3636                case 'qmumean',
    3737                        plot_qmumean(md,options,nlines,ncols,i);
    3838                        return;
    39                
     39
    4040                case 'qmustddev',
    4141                        plot_qmustddev(md,options,nlines,ncols,i);
    4242                        return;
    43                
     43
    4444                case 'qmuhistnorm',
    4545                        plot_qmuhistnorm(md,options,nlines,ncols,i);
     
    118118                        plot_segments(md,options,subplotwidth,i,data)
    119119                        return
    120                
     120
    121121                case 'quiver'
    122122                        data=[md.initialization.vx md.initialization.vy]; %Go ahead and try plot_unit
     
    199199                error('cannot kmlgroundoverlay on multi-plots');
    200200        end
    201        
     201
    202202        %call routine to build kml file and image that goes with it.
    203203        kmlgroundoverlay(md,options);
  • issm/trunk/src/m/plot/plot_mesh.m

    r13395 r13975  
    1 function plot_mesh(md,options,nlines,ncols,i);
     1function plot_mesh(md,options,nlines,ncols,i)
    22%PLOT_MESH - plot model mesh
    33%
  • issm/trunk/src/m/plot/plot_none.m

    r13395 r13975  
    1 function plot_none(md,options,nlines,ncols,i);
     1function plot_none(md,options,nlines,ncols,i)
    22%PLOT_NONE - plot nothing, just apply options
    33%
  • issm/trunk/src/m/plot/plot_overlay.m

    r13395 r13975  
    2525        error('buildoverlay error message: overlay not supported for quiver plots');
    2626end
    27 
    2827
    2928%radar power
     
    150149        options=changefieldvalue(options,'caxis',[data_min data_max]); % force caxis so that the colorbar is ready
    151150end
    152 options=addfielddefault(options,'axis','equal off');              % default axis
     151options=addfielddefault(options,'xlim',xlim);        % default xlim
     152options=addfielddefault(options,'ylim',ylim);        % default ylim
     153options=addfielddefault(options,'axis','equal off'); % default axis
    153154applyoptions(md,data,options);
    154155drawnow
  • issm/trunk/src/m/plot/plot_parthist.m

    r13395 r13975  
    1 function plot_parthist(md,options,nlines,ncols,i);
     1function plot_parthist(md,options,nlines,ncols,i)
    22%PLOT_PARTHIST - plot partitioning histogram
    33%
  • issm/trunk/src/m/plot/plot_parthistn.m

    r13395 r13975  
    1 function plot_parthist(md,options,nlines,ncols,i);
     1function plot_parthist(md,options,nlines,ncols,i)
    22%PLOT_PARTHIST - plot partitioning histogram
    33%
  • issm/trunk/src/m/plot/plot_parthistw.m

    r13395 r13975  
    1 function plot_parthist(md,options,nlines,ncols,i);
     1function plot_parthist(md,options,nlines,ncols,i)
    22%PLOT_PARTHIST - plot partitioning histogram
    33%
  • issm/trunk/src/m/plot/plot_penalties.m

    r13395 r13975  
    1 function plot_penalties(md,options,width,i);
     1function plot_penalties(md,options,width,i)
    22%PLOT_PENALTIES - plot penalties
    33%
  • issm/trunk/src/m/plot/plot_qmu_mass_flux_segments.m

    r13395 r13975  
    1 function plot_qmu_mass_flux_segments(md,options,nlines,ncols,i);
     1function plot_qmu_mass_flux_segments(md,options,nlines,ncols,i)
    22%PLOT_QMU_MASS_FLUX_SEGMENTS - plot segments from the qmu analysis of mass fluxes
    33%
     
    2727
    2828                %plot normals
    29                
     29
    3030                for j=1:length(segments),
    3131                        xstart=mean([segments(j,1) segments(j,3)]);
  • issm/trunk/src/m/plot/plot_qmuhistnorm.m

    r13395 r13975  
    1 function plot_qmuhistnorm(md,options,nlines,ncols,index);
     1function plot_qmuhistnorm(md,options,nlines,ncols,index)
    22
    33%prepare plot
    44subplot(nlines,ncols,index);
    55hold on
    6 
    76
    87%recover histnorm data
  • issm/trunk/src/m/plot/plot_qmumean.m

    r13395 r13975  
    1 function plot_qmumean(md,options,nlines,ncols,i);
     1function plot_qmumean(md,options,nlines,ncols,i)
    22%PLOT_QMUMEAN - plot mean of a scaled response
    33%
  • issm/trunk/src/m/plot/plot_qmustddev.m

    r13395 r13975  
    1 function plot_qmustddev(md,options,nlines,ncols,i);
     1function plot_qmustddev(md,options,nlines,ncols,i)
    22%PLOT_QMUMEAN - plot stddev of a scaled response
    33%
     
    4747end
    4848
    49 
    5049%now, project onto vertices
    5150responses_on_node=responses(md.qmu.partition+1);
  • issm/trunk/src/m/plot/plot_referential.m

    r13395 r13975  
    1 function plot_referential(md,options,width,i,data);
     1function plot_referential(md,options,width,i,data)
    22%PLOT_PRESSURELOAD - plot segment on neumann BC
    33%
  • issm/trunk/src/m/plot/plot_riftfraction.m

    r13395 r13975  
    1 function plot_riftfraction(md,options,nlines,ncols,index);
     1function plot_riftfraction(md,options,nlines,ncols,index)
    22%PLOT_RIFTFRACTION - plot rift fractions
    33%
  • issm/trunk/src/m/plot/plot_riftnumbering.m

    r13395 r13975  
    1 function plot_riftnumbering(md,options,nlines,ncols,index);
     1function plot_riftnumbering(md,options,nlines,ncols,index)
    22%PLOT_RIFTNUMBERING - plot rift penetration + numbering of all rift vertices, as well as rift numbers.
    33%
     
    8888end
    8989
    90 
    9190%apply options
    9291options=addfielddefault(options,'title','Rift/Fault location');
  • issm/trunk/src/m/plot/plot_riftpenetration.m

    r13395 r13975  
    1 function plot_rifpenetration(md,options,nlines,ncols,index);
     1function plot_rifpenetration(md,options,nlines,ncols,index)
    22%PLOT_RIFTPENETRATION - plot rift penetration
    33%
  • issm/trunk/src/m/plot/plot_riftrelvel.m

    r13395 r13975  
    1 function plot_riftrelvel(md,options,nlines,ncols,index);
     1function plot_riftrelvel(md,options,nlines,ncols,index)
    22%PLOT_RIFTRELVEL - plot rift relative velocities
    33%
     
    1515end
    1616options=addfielddefault(options,'scaling',2);
     17
     18%markersize:
     19markersize=getfieldvalue(options,'markersize',1);
    1720
    1821%recover vx and vy:
     
    3841hold on
    3942
    40 %plot mesh boundaries
    41 for i=1:size(md.mesh.segments,1),
    42         plot(x(md.mesh.segments(i,1:2)),y(md.mesh.segments(i,1:2)),'k-');
    43 end
    44 
    4543%plot rifts vel
    4644h3=[];
     
    6361end
    6462for i=1:size(md.rifts.riftstruct,1),
    65        
     63
    6664        %get nodes on rift
    6765        penaltypairs=md.rifts.riftstruct(i).penaltypairs;
     
    8179                %if penetration is negative, plot in black, positive, plot in red;: ie: if rift is closing, black, if rift is opening, red.
    8280                if(penetration>0),
    83                         p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'*'); set(p2,'Color',[140 140 140]/255);
     81                        p2=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'.','MarkerSize',markersize); set(p2,'Color',[140 140 140]/255);
    8482                        isp2=1;
    8583                else
    86                         p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'k*');
     84                        p1=plot(x(penaltypairs(j,1)) ,y(penaltypairs(j,1)),'k.','MarkerSize',markersize);
    8785                        isp1=1;
    8886                end
     
    9088
    9189        %point out the tips
    92         h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g*');
    93         plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g*');
     90        h2=plot(x(md.rifts.riftstruct(i).tips(1)),y(md.rifts.riftstruct(i).tips(1)),'g.','MarkerSize',markersize);
     91        plot(x(md.rifts.riftstruct(i).tips(2)),y(md.rifts.riftstruct(i).tips(2)),'g.','MarkerSize',markersize);
    9492        segments=md.rifts.riftstruct(i).segments(:,1:2);
    9593end
     94
     95faulttitle=getfieldvalue(options','faulttitle','faults');
     96rifttitle=getfieldvalue(options','rifttitle','rifts');
    9697%legend
    9798if strcmpi(getfieldvalue(options,'legend','on'),'on'),
    9899        if isp1 & isp2
    99                 l=legend([h1,h2,p1,p2],'mesh boundaries','crack tips','faults','rifts');
     100                l=legend([h1,h2,p1,p2],'mesh boundaries','crack tips',faulttitle,rifttitle);
    100101        elseif isp1
    101                 l=legend([h1,h2,p1],'mesh boundaries','crack tips','faults');
     102                l=legend([h1,h2,p1],'mesh boundaries','crack tips',faulttitle);
    102103        elseif isp2
    103                 l=legend([h1,h2,p2],'mesh boundaries','crack tips','rifts');
     104                l=legend([h1,h2,p2],'mesh boundaries','crack tips',rifttitle);
    104105        else
    105106                l=legend([h1,h2],'mesh boundaries','crack tips');
  • issm/trunk/src/m/plot/plot_rifts.m

    r13395 r13975  
    1 function plot_rifts(md,options,nlines,ncols,index);
     1function plot_rifts(md,options,nlines,ncols,index)
    22%PLOT_RIFTS - plot rifts in a mesh
    33%
     
    1616offset=getfieldvalue(options,'offset',500);
    1717if isstruct(md.rifts.riftstruct),
    18        
     18
    1919        for i=1:size(md.rifts.riftstruct,1),
    2020                penaltypairs=md.rifts.riftstruct(i).penaltypairs;
  • issm/trunk/src/m/plot/plot_riftvel.m

    r13395 r13975  
    1 function plot_riftvel(md,options,nlines,ncols,index);
     1function plot_riftvel(md,options,nlines,ncols,index)
    22%PLOT_RIFTVEL - plot rift velocity
    33%
     
    8989end
    9090
    91 
    9291%legend
    9392if isp1 & isp2
  • issm/trunk/src/m/plot/plot_sarpwr.m

    r13395 r13975  
    1 function plot_sarpwr(md,options,width,i);
     1function plot_sarpwr(md,options,width,i)
    22%PLOT_SARPWR - plot radar image
    33%
     
    1717        md.mesh.z=md.mesh.z*unit;
    1818end
    19                                        
     19
    2020imagesc(md.radaroverlay.x,md.radaroverlay.y,double(md.radaroverlay.pwr)),set(gca,'YDir','normal');colormap(gray);
    2121
  • issm/trunk/src/m/plot/plot_scatter.m

    r13395 r13975  
    1 function plot_scatter(x,y,level,options),
     1function plot_scatter(x,y,level,varargin),
    22
    3 if nargin==3, options=pairoptions(); end
     3options=pairoptions(varargin{:});
    44
    55%check input
     
    1313Siz=length(level);
    1414nlab=10;
     15%Min=0;
     16%Max=1300;
    1517
    1618%OK, should we create a new colorbar for the occasion?
  • issm/trunk/src/m/plot/plot_section.m

    r13395 r13975  
    115115                        hold on
    116116
    117 
    118117                        %3D
    119118                else
  • issm/trunk/src/m/plot/plot_segments.m

    r13395 r13975  
    1 function plot_segments(md,options,width,i,datai);
     1function plot_segments(md,options,width,i,datai)
    22%PLOT_SEGMENTS - plot segments, with different colors according to segment markers.
    33%
     
    4242        h3=plot(xstart,ystart,'r*');
    4343
    44 
    4544else
    4645        error('plot_segments: 3d plot of segments not supported yet!');
  • issm/trunk/src/m/plot/plot_tensor.m

    r13395 r13975  
    1 function plot_tensor(md,options,width,i,type);
     1function plot_tensor(md,options,width,i,type)
    22%PLOT_TENSOR - plot tensor components
    33%
  • issm/trunk/src/m/plot/plot_tensor_components.m

    r13395 r13975  
    1 function plot_tensor_components(md,options,width,i,tensor,type,plot_options);
     1function plot_tensor_components(md,options,width,i,tensor,type,plot_options)
    22%PLOT_TENSOR_COMPONENT - plot component of a tensor
    33%
  • issm/trunk/src/m/plot/plot_tensor_principal.m

    r13395 r13975  
    1 function plot_tensor_principal(md,options,width,i,tensor,type,plot_options);
     1function plot_tensor_principal(md,options,width,i,tensor,type,plot_options)
    22%PLOT_TENSOR_PRINCIPAL - plot principal values
    33%
  • issm/trunk/src/m/plot/plot_tensor_principalaxis.m

    r13395 r13975  
    1 function plot_tensor_principalaxis(md,options,width,i,tensor,type,plot_options);
     1function plot_tensor_principalaxis(md,options,width,i,tensor,type,plot_options)
    22%PLOT_TENSOR_PRINCIPALAXIS - plot ytensor principal axis
    33%
  • issm/trunk/src/m/plot/plot_thermaltransient_results.m

    r13395 r13975  
    2222eval(string);
    2323clear string;
    24 
  • issm/trunk/src/m/plot/plot_transient_movie.m

    r13395 r13975  
    1 function plot_transient_movie(md,options,width,i);
     1function plot_transient_movie(md,options,width,i)
    22%PLOT_TRANSIENT_MOVIE - plot a transient result as a movie
    33%   Usage:
  • issm/trunk/src/m/plot/plot_vertexnumbering.m

    r13395 r13975  
    1 function plot_vertexnumbering(md,options,width,i);
     1function plot_vertexnumbering(md,options,width,i)
    22%PLOT_VERTEXNUMBERING - plot vertex numbering
    33%
     
    2525        %Highlight
    2626        pos=getfieldvalue(options,'highlight',[]);
    27         text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
     27        text(x(pos),y(pos),z(pos),num2str(pos(:)),...
    2828                'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
    2929else
     
    4242        %Highlight
    4343        pos=getfieldvalue(options,'highlight',[]);
    44         text(x(pos),y(pos),z(pos),num2str(transpose(pos)),...
     44        text(x(pos),y(pos),z(pos),num2str(pos(:)),...
    4545                'backgroundcolor',[1 0 0],'HorizontalAlignment','center','VerticalAlignment','middle');
    4646end
  • issm/trunk/src/m/plot/plotmodel.m

    r13395 r13975  
    3232%go through subplots
    3333if numberofplots,
    34                
     34
    3535        %Create figure
    3636        if strcmpi(getfieldvalue(options.list{1},'visible','on'),'off'),
  • issm/trunk/src/m/plot/processdata.m

    r13395 r13975  
    1 function [data datatype]=processdata(md,data,options);
     1function [data datatype]=processdata(md,data,options)
    22%PROCESSDATA - process data to be plotted
    33%
     
    4848end
    4949
    50 %get datatype
     50%get datasize
    5151datasize=size(data);
    5252
    53 %Process NaN if any (do not now before mask is applied)
     53%Process NaN if any (do not know before mask is applied)
    5454if exist(options,'nan')
    5555        data(find(isnan(data)))=getfieldvalue(options,'nan',0);
     
    7474                error('plotmodel error message: data not supported yet');
    7575        end
    76        
     76
    7777        %quiver?
    7878        if datasize(2)>1,
  • issm/trunk/src/m/plot/processmesh.m

    r13395 r13975  
    1 function [x y z elements is2d isplanet]=processmesh(md,data,options);
     1function [x y z elements is2d isplanet]=processmesh(md,data,options)
    22%PROCESSMESH - process mesh to be plotted
    33%
     
    3636                z=md.mesh.z;
    3737        end
    38 
    3938
    4039        if isprop(md.mesh,'elements2d'), elements2d=md.mesh.elements2d; end
  • issm/trunk/src/m/plot/quiver_colorbar.m

    r13395 r13975  
    3131        fontsize=getfieldvalue(options,'fontsize',14);
    3232        set(hcb,'FontSize',fontsize);
    33        
     33
    3434        if exist(options,'colorbartitle'),
    3535                backup=gca;
  • issm/trunk/src/m/plot/radarpower.m

    r13395 r13975  
    3232if ~exist(options,'overlay_image'),
    3333        if strcmpi(md.mesh.hemisphere,'n'),
    34                 %if ~exist([jplsvn() '/projects/ModelData/MOG/mog150_greenland_map.jpg']),
    35                 %       error(['radarpower error message: file ' jplsvn() '/projects/ModelData/MOG/mog150_greenland_map.jpg not found.']);
     34                %if ~exist(['/u/astrid-r1b/ModelData/MOG/mog150_greenland_map.jpg']),
     35                %       error(['radarpower error message: file ' '/u/astrid-r1b/ModelData/MOG/mog150_greenland_map.jpg not found.']);
    3636                %end
    3737                %name = 'mog150_greenland_map';
    3838                %name = 'mog100_hp1_v10';
    3939                %%name = 'mog500_hp1_v10';
    40                 %jpgim=[jplsvn() '/projects/ModelData/MOG/' name '.jpg'];
    41                 %geom=load([jplsvn() '/projects/ModelData/MOG/' name '.jpgw'],'ascii');
     40                %jpgim=['/u/astrid-r1b/ModelData/MOG/' name '.jpg'];
     41                %geom=load(['/u/astrid-r1b/ModelData/MOG/' name '.jpgw'],'ascii');
    4242                %%jpgim='/u/astrid-r1b/morlighe/issmjpl/projects/MorlighemGRL2012/Data/Mosaic_amp_asar2010.jpg';
    4343                %%geom=load('/u/astrid-r1b/morlighe/issmjpl/projects/MorlighemGRL2012/Data/Mosaic_amp_asar2010.jpgw');
     
    6565                %md.radaroverlay.y=(ymin:(ymax-ymin)/(size(md.radaroverlay.pwr,1)-1):ymax);
    6666                if highres,
    67                         if ~exist([jplsvn() '/projects/ModelData/MOG/mog100g_r2_hp1.tif']),
    68                                 error(['radarpower error message: file ' jplsvn() '/projects/ModelData/MOG/mog100g_r2_hp1.tif not found.']);
     67                        if ~exist(['/u/astrid-r1b/ModelData/MOG/mog100_r2_hp1.tif']),
     68                                error(['radarpower error message: file ' '/u/astrid-r1b/ModelData/MOG/mog100_r2_hp1.tif not found.']);
    6969                        end
    70                         geotiff_name=[jplsvn() '/projects/ModelData/MOG/mog100_r2_hp1.tif'];
     70                        geotiff_name=['/u/astrid-r1b/ModelData/MOG/mog100_r2_hp1.tif'];
    7171                else
    72                         if ~exist([jplsvn() '/projects/ModelData/MOG/mog500g_r2_hp1.tif']),
    73                                 error(['radarpower error message: file ' jplsvn() '/projects/ModelData/MOG/mog500g_r2_hp1.tif not found.']);
     72                        if ~exist(['/u/astrid-r1b/ModelData/MOG/mog500_r2_hp1.tif']),
     73                                error(['radarpower error message: file ' '/u/astrid-r1b/ModelData/MOG/mog500_r2_hp1.tif not found.']);
    7474                        end
    75                         geotiff_name=[jplsvn() '/projects/ModelData/MOG/mog500_r2_hp1.tif'];
     75                        geotiff_name=['/u/astrid-r1b/ModelData/MOG/mog500_r2_hp1.tif'];
    7676                end
    7777
     
    9090                system('rm -rf ./temp.tif');
    9191
    92 
    9392        elseif strcmpi(md.mesh.hemisphere,'s'),
    9493                if highres,
    95                         if ~exist([jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif']),
    96                                 error(['radarpower error message: file ' jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif not found.']);
     94                        if ~exist(['/u/astrid-r1b/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif']),
     95                                error(['radarpower error message: file ' '/u/astrid-r1b/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif not found.']);
    9796                        end
    98                         geotiff_name=[jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif'];
     97                        geotiff_name=['/u/astrid-r1b/ModelData/MosaicTiffRsat/amm125m_v2_200m.tif'];
    9998                else
    100                         if ~exist([jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif']),
    101                                 error(['radarpower error message: file ' jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif not found.']);
     99                        if ~exist(['/u/astrid-r1b/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif']),
     100                                error(['radarpower error message: file ' '/u/astrid-r1b/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif not found.']);
    102101                        end
    103                         geotiff_name=[jplsvn() '/projects/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif'];
     102                        geotiff_name=['/u/astrid-r1b/ModelData/MosaicTiffRsat/amm125m_v2_1km.tif'];
    104103                end
    105104
  • issm/trunk/src/m/plot/subplotmodel.m

    r13395 r13975  
    1 function ha=subplotmodel(nlines,ncols,num,options);
     1function ha=subplotmodel(nlines,ncols,num,options)
    22%SUBPLOTMODEL -  tight subplot that includes margins
    33%
  • issm/trunk/src/m/print/printmodel.m

    r13395 r13975  
    2323%      printmodel('image','tiff')
    2424%      printmodel('image','eps','margin','on','frame','on','hardcopy','on')
    25 
    2625
    2726%get options:
     
    5453%InvertHardcopy off imposes MATLAB to use the same colors
    5554set(fig, 'InvertHardcopy', getfieldvalue(options,'hardcopy'));
    56 
    5755
    5856%we could have several formats, as a cell array of strings.
  • issm/trunk/src/m/qmu/MassFluxProcessProfile.m

    r4773 r13975  
    1 function segments=MassFluxProcessProfile(md,directory,profilename);
     1function segments=MassFluxProcessProfile(md,directory,profilename)
    22%MASSFLUXPROCESSPROFILE: process an argus domain outlien profile into a list of segments.
    33%
     
    77% See also: PROCESS_QMU_RESPONSE_DATA, PREQMU
    88
    9 
    109%first read the profile points.
    1110profile=expread([directory '/' profilename]);
  • issm/trunk/src/m/qmu/dakota_cdfs.m

    r3092 r13975  
    136136        end
    137137    end
    138    
     138
    139139    varargout{1}=dresp;
    140    
     140
    141141elseif exist('samp','var') && ~isempty(samp)
    142142    cdf=zeros(length(resp)+length(prob)+length(rel)+length(grel),...
     
    147147            resp,prob,rel,grel);
    148148    end
    149    
     149
    150150    varargout{1}=cdf;
    151    
     151
    152152elseif exist('mean','var'  ) && ~isempty(mean  ) && ...
    153153       exist('stddev','var') && ~isempty(stddev)
     
    159159            resp,prob,rel,grel);
    160160    end
    161    
     161
    162162    varargout{1}=cdf;
    163163else
     
    178178    mu   =mean(samp);
    179179    sigma=std(samp);
    180    
     180
    181181    cdf=zeros(length(resp)+length(prob)+length(rel)+length(grel),4);
    182182    cdf(:,:)=NaN;
  • issm/trunk/src/m/qmu/dakota_in_data.m

    r11995 r13975  
    8888% dmeth=dmeth_params_merge(dmeth,dparams)
    8989
    90 
    9190%%  variables
    9291
     
    9998
    10099end
    101    
     100
    102101%%  responses
    103102
  • issm/trunk/src/m/qmu/dakota_in_params.m

    r5486 r13975  
    209209
    210210end
    211 
  • issm/trunk/src/m/qmu/dakota_in_parse.m

    r1014 r13975  
    4242%
    4343function [method,dvar,dresp]=dakota_in_parse(filei)
    44    
     44
    4545if ~nargin
    4646    help dakota_in_parse
     
    631631
    632632itoken=itoken+1;
    633    
     633
    634634%  read next line if necessary
    635635
     
    644644    itoken=1;
    645645end
    646    
     646
    647647end
    648648
     
    668668    itoken=1;
    669669end
    670    
     670
    671671%  check for equal sign and skip
    672672
  • issm/trunk/src/m/qmu/dakota_moments.m

    r3092 r13975  
    8989            moments_calc(dresp(i).sample,alpha);
    9090    end
    91    
     91
    9292    varargout{1}=dresp;
    93    
     93
    9494elseif exist('samp','var') && ~isempty(samp)
    9595    mean    =zeros(1,size(samp,2));
     
    106106            moments_calc(samp(:,i),alpha);
    107107    end
    108    
     108
    109109    varargout{1}=mean;
    110110    varargout{2}=stddev;
  • issm/trunk/src/m/qmu/dakota_out_parse.m

    r6690 r13975  
    170170end
    171171display(sprintf('Number of columns (Dakota V+R)=%d.',ntokens-1));
    172    
     172
    173173%  process rows of matrix
    174174
     
    301301    end
    302302    [ntokens,tokens]=fltokens(fline);
    303    
     303
    304304%  add new response function and moments
    305305
     
    336336    end
    337337    [ntokens,tokens]=fltokens(fline);
    338    
     338
    339339%  find response function associated with confidence intervals
    340340
     
    464464    cmat.row   =cell(1,1);
    465465    cmat.matrix=zeros(1,ntokens);
    466    
     466
    467467    for i=1:ntokens
    468468        cmat.column(1,i)=cellstr(tokens{1}{i});
    469469    end
    470    
     470
    471471%  process rows of matrix, reading until blank line
    472472
     
    583583            display(sprintf('  %s',dresp(idresp).descriptor));
    584584        end
    585    
     585
    586586%  skip column headings of cdf
    587587
  • issm/trunk/src/m/qmu/examples/direct.m

    r9650 r13975  
    44md.qmu.params.evaluation_concurrency=1;
    55
    6 
    7 
    86%or for matlab direct driver
    97md.qmu.params.direct=true;
  • issm/trunk/src/m/qmu/examples/lrel_mmf.m

    r9650 r13975  
    9393%part_hist(md.qmu.partition,md.vertex_weight)
    9494%plotmodel(md,'data',log10(md.results.dakota.dresp_out(9).impfac(md.qmu.partition+1)))
    95 
  • issm/trunk/src/m/qmu/expandvariables.m

    r9668 r13975  
    44
    55for i=1:length(fnames)
    6    
     6
    77%  for linear constraints, just copy
    88
  • issm/trunk/src/m/qmu/importancefactors.m

    r9742 r13975  
    88%   Example: factors=importancefactors(md,'drag','max_vel');
    99%
    10 
    1110
    1211variablenamelength=length(variablename);
  • issm/trunk/src/m/qmu/lclist_write.m

    r13395 r13975  
    6060
    6161end
    62 
  • issm/trunk/src/m/qmu/plot/plot_boxplot.m

    r7398 r13975  
    6262    dresp=varargin{iarg};
    6363    iarg=iarg+1;
    64    
     64
    6565%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    6666    if iarg <= nargin && iscell(varargin{iarg})
     
    6868        iarg=iarg+1;
    6969    end
    70    
     70
    7171    descr=cell (1,length(dresp));
    7272    lsamp=zeros(1,length(dresp));
     
    8484    sampr=varargin{iarg};
    8585    iarg=iarg+1;
    86    
     86
    8787    if     iarg <= nargin && iscell(varargin{iarg})
    8888        descr=varargin{iarg};
     
    119119    iarg=iarg+2;
    120120end
    121    
     121
    122122%%  draw the plot
    123123
  • issm/trunk/src/m/qmu/plot/plot_cdf.m

    r7398 r13975  
    7777    dresp=varargin{iarg};
    7878    iarg=iarg+1;
    79    
     79
    8080%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    8181    if iarg <= nargin && iscell(varargin{iarg})
     
    188188    set(hl1(i),'Color',cmap(imap,:))
    189189end
    190    
     190
    191191xlim('auto')
    192192[xlims]=xlim;
     
    278278        end
    279279    end
    280    
     280
    281281    if strcmpi(pdfplt,'line')
    282282        xplot=xpdf;
  • issm/trunk/src/m/qmu/plot/plot_hist_norm.m

    r8732 r13975  
    8989    dresp1=varargin{iarg};
    9090    iarg=iarg+1;
    91    
     91
    9292%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    9393    if iarg <= nargin && iscell(varargin{iarg})
     
    9595        iarg=iarg+1;
    9696    end
    97    
     97
    9898    descr=cell (1,length(dresp1));
    9999    lsamp=zeros(1,length(dresp1));
     
    111111    sampr=varargin{iarg};
    112112    iarg=iarg+1;
    113    
     113
    114114    lsamp(1:size(sampr,2))=size(sampr,1);
    115115
     
    142142        iarg=iarg+1;
    143143    end
    144    
     144
    145145    mu   =zeros(1,length(dresp2));
    146146    sigma=zeros(1,length(dresp2));
     
    298298    end
    299299end
    300    
     300
    301301xlim('auto')
    302302[xlims]=xlim;
  • issm/trunk/src/m/qmu/plot/plot_hist_norm_ci.m

    r7398 r13975  
    7878    dresp=varargin{iarg};
    7979    iarg=iarg+1;
    80    
     80
    8181%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    8282    if iarg <= nargin && iscell(varargin{iarg})
     
    8484        iarg=iarg+1;
    8585    end
    86    
     86
    8787    descr=cell (1,length(dresp));
    8888    lsamp=zeros(1,length(dresp));
     
    9292    sampr=zeros(max(lsamp),length(dresp));
    9393    sampr(:,:)=NaN;
    94    
     94
    9595    mu     =zeros(1,length(dresp));
    9696    sigma  =zeros(1,length(dresp));
     
    109109    sampr=varargin{iarg};
    110110    iarg=iarg+1;
    111    
     111
    112112    lsamp(1:size(sampr,2))=size(sampr,1);
    113113
     
    121121        descr=cell(1,size(sampr,2));
    122122    end
    123    
     123
    124124    mu     =zeros(1,size(sampr,2));
    125125    sigma  =zeros(1,size(sampr,2));
     
    325325    end
    326326end
    327    
     327
    328328xlim('auto')
    329329[xlims]=xlim;
  • issm/trunk/src/m/qmu/plot/plot_if_bars.m

    r7398 r13975  
    6666    dresp=varargin{iarg};
    6767    iarg=iarg+1;
    68    
     68
    6969%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    7070    if iarg <= nargin && iscell(varargin{iarg})
     
    7272        iarg=iarg+1;
    7373    end
    74    
     74
    7575    descr=cell (1,length(dresp));
    7676    lifr =zeros(1,length(dresp));
     
    125125    end
    126126    clear ifmean
    127    
     127
    128128    dvar=dvar(index);
    129129    ifr =ifr (:,index);
     
    136136    dvar(nif+1,1)=cellstr(sprintf('others < %f',ifmin));
    137137    ifr (:,nif+1)=0.;
    138    
     138
    139139    nif2=0;
    140140    dvar2=cell (size(dvar));
    141141    ifr2 =zeros(size(ifr ));
    142    
     142
    143143%  sum filtered rows and copy unfiltered rows
    144144
     
    152152        end
    153153    end
    154    
     154
    155155%  copy sums
    156156
    157157    dvar2(nif2+1)  =dvar(nif+1);
    158158    ifr2 (:,nif2+1)=ifr (:,nif+1);
    159    
     159
    160160%  copy back and truncate filtered rows
    161161
  • issm/trunk/src/m/qmu/plot/plot_if_spec.m

    r7398 r13975  
    7272    dresp=varargin{iarg};
    7373    iarg=iarg+1;
    74    
     74
    7575%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    7676    if iarg <= nargin && iscell(varargin{iarg})
     
    7878        iarg=iarg+1;
    7979    end
    80    
     80
    8181    descr=cell (1,length(dresp));
    8282    lifr =zeros(1,length(dresp));
     
    137137    end
    138138    clear ifmean
    139    
     139
    140140    dvar=dvar(index);
    141141    ifr =ifr (:,index);
     
    148148    dvar(nif+1,1)=cellstr(sprintf('others < %f',ifmin));
    149149    ifr (:,nif+1)=0.;
    150    
     150
    151151    nif2=0;
    152152    dvar2=cell (size(dvar));
    153153    ifr2 =zeros(size(ifr ));
    154    
     154
    155155%  sum filtered rows and copy unfiltered rows
    156156
     
    164164        end
    165165    end
    166    
     166
    167167%  copy sums
    168168
    169169    dvar2(nif2+1)  =dvar(nif+1);
    170170    ifr2 (:,nif2+1)=ifr (:,nif+1);
    171    
     171
    172172%  copy back and truncate filtered rows
    173173
  • issm/trunk/src/m/qmu/plot/plot_normdist_bars.m

    r7398 r13975  
    7373    dresp=varargin{iarg};
    7474    iarg=iarg+1;
    75    
     75
    7676%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    7777    if iarg <= nargin && iscell(varargin{iarg})
     
    8282    sampr=varargin{iarg};
    8383    iarg=iarg+1;
    84    
     84
    8585    if     iarg <= nargin && iscell(varargin{iarg})
    8686        descr=varargin{iarg};
     
    9292        descr=cell(1:size(sampr,2));
    9393    end
    94    
     94
    9595    dresp=struct([]);
    9696    for i=1:size(sampr,2)
  • issm/trunk/src/m/qmu/plot/plot_normplot.m

    r7398 r13975  
    6262    dresp=varargin{iarg};
    6363    iarg=iarg+1;
    64    
     64
    6565%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    6666    if iarg <= nargin && iscell(varargin{iarg})
     
    6868        iarg=iarg+1;
    6969    end
    70    
     70
    7171    descr=cell (1,length(dresp));
    7272    lsamp=zeros(1,length(dresp));
     
    8484    sampr=varargin{iarg};
    8585    iarg=iarg+1;
    86    
     86
    8787    if     iarg <= nargin && iscell(varargin{iarg})
    8888        descr=varargin{iarg};
     
    119119    iarg=iarg+2;
    120120end
    121    
     121
    122122%%  draw the plot
    123123
  • issm/trunk/src/m/qmu/plot/plot_prob_bars.m

    r7398 r13975  
    5757%%  assemble the data into a matrix and calculate the increments
    5858
    59 
    6059%%  process input data and assemble into matrices and increments
    6160
     
    6665    dresp=varargin{iarg};
    6766    iarg=iarg+1;
    68    
     67
    6968%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    7069    if iarg <= nargin && iscell(varargin{iarg})
     
    7271        iarg=iarg+1;
    7372    end
    74    
     73
    7574    descr=cell (1,length(dresp));
    7675    lcdfr=zeros(1,length(dresp));
  • issm/trunk/src/m/qmu/plot/plot_rlev_bars.m

    r7398 r13975  
    6262    dresp=varargin{iarg};
    6363    iarg=iarg+1;
    64    
     64
    6565%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    6666    if iarg <= nargin && iscell(varargin{iarg})
     
    6868        iarg=iarg+1;
    6969    end
    70    
     70
    7171    descr=cell (1,length(dresp));
    7272    lcdfr=zeros(1,length(dresp));
  • issm/trunk/src/m/qmu/plot/plot_rlev_bars_ci.m

    r7398 r13975  
    7474    dresp=varargin{iarg};
    7575    iarg=iarg+1;
    76    
     76
    7777%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    7878    if iarg <= nargin && iscell(varargin{iarg})
     
    8383    sampr=varargin{iarg};
    8484    iarg=iarg+1;
    85    
     85
    8686    if     iarg <= nargin && iscell(varargin{iarg})
    8787        descr=varargin{iarg};
     
    9393        descr=cell(1:size(sampr,2));
    9494    end
    95    
     95
    9696    dresp=struct([]);
    9797    for i=1:size(sampr,2)
     
    136136        display('Using calculated normal fits from sample data.')
    137137    end
    138    
     138
    139139    if ~isfield(dresp(i),'cdf') || isempty(dresp(i).cdf)
    140140%  use minus/plus integer standard deviations
  • issm/trunk/src/m/qmu/plot/plot_rvsv_line.m

    r7398 r13975  
    7474    dvar=varargin{iarg};
    7575    iarg=iarg+1;
    76    
     76
    7777%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    7878    if iarg <= nargin && iscell(varargin{iarg})
     
    8080        iarg=iarg+1;
    8181    end
    82    
     82
    8383    descv=cell (1,length(dvar));
    8484    lsamp=zeros(1,length(dvar));
     
    9696    sampv=varargin{iarg};
    9797    iarg=iarg+1;
    98    
     98
    9999    if     iarg <= nargin && iscell(varargin{iarg})
    100100        descv=varargin{iarg};
     
    119119    dresp=varargin{iarg};
    120120    iarg=iarg+1;
    121    
     121
    122122%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    123123    if iarg <= nargin && iscell(varargin{iarg})
     
    125125        iarg=iarg+1;
    126126    end
    127    
     127
    128128    descr=cell (1,length(dresp));
    129129    lsamp=zeros(1,length(dresp));
     
    141141    sampr=varargin{iarg};
    142142    iarg=iarg+1;
    143    
     143
    144144    if     iarg <= nargin && iscell(varargin{iarg})
    145145        descr=varargin{iarg};
     
    177177    iarg=iarg+2;
    178178end
    179    
     179
    180180if     ~exist('nplotr','var') && ~exist('nplotc','var')
    181181    nplotr=1;
     
    225225                'IconDisplayStyle','off'); % Exclude line from legend
    226226        end
    227        
     227
    228228%  add the annotation
    229229
  • issm/trunk/src/m/qmu/plot/plot_rvsv_scat3.m

    r7398 r13975  
    7979    dvar=varargin{iarg};
    8080    iarg=iarg+1;
    81    
     81
    8282%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    8383    if iarg <= nargin && iscell(varargin{iarg})
     
    8585        iarg=iarg+1;
    8686    end
    87    
     87
    8888    descv=cell (1,length(dvar));
    8989    lsamp=zeros(1,length(dvar));
     
    101101    sampv=varargin{iarg};
    102102    iarg=iarg+1;
    103    
     103
    104104    if     iarg <= nargin && iscell(varargin{iarg})
    105105        descv=varargin{iarg};
     
    128128    dresp=varargin{iarg};
    129129    iarg=iarg+1;
    130    
     130
    131131%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    132132    if iarg <= nargin && iscell(varargin{iarg})
     
    134134        iarg=iarg+1;
    135135    end
    136    
     136
    137137    descr=cell (1,length(dresp));
    138138    lsamp=zeros(1,length(dresp));
     
    150150    sampr=varargin{iarg};
    151151    iarg=iarg+1;
    152    
     152
    153153    if     iarg <= nargin && iscell(varargin{iarg})
    154154        descr=varargin{iarg};
     
    187187    iarg=iarg+2;
    188188end
    189    
     189
    190190if     ~exist('nplotr','var') && ~exist('nplotc','var')
    191191    nplotr=ceil(sqrt(size(sampr,2)));
     
    208208
    209209for iresp=1:size(sampr,2)
    210    
     210
    211211%  initialize the subplot
    212212
  • issm/trunk/src/m/qmu/plot/plot_rvsv_surf.m

    r7398 r13975  
    7676    dvar=varargin{iarg};
    7777    iarg=iarg+1;
    78    
     78
    7979%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    8080    if iarg <= nargin && iscell(varargin{iarg})
     
    8282        iarg=iarg+1;
    8383    end
    84    
     84
    8585    descv=cell (1,length(dvar));
    8686    lsamp=zeros(1,length(dvar));
     
    9898    sampv=varargin{iarg};
    9999    iarg=iarg+1;
    100    
     100
    101101    if     iarg <= nargin && iscell(varargin{iarg})
    102102        descv=varargin{iarg};
     
    125125    dresp=varargin{iarg};
    126126    iarg=iarg+1;
    127    
     127
    128128%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    129129    if iarg <= nargin && iscell(varargin{iarg})
     
    131131        iarg=iarg+1;
    132132    end
    133    
     133
    134134    descr=cell (1,length(dresp));
    135135    lsamp=zeros(1,length(dresp));
     
    147147    sampr=varargin{iarg};
    148148    iarg=iarg+1;
    149    
     149
    150150    if     iarg <= nargin && iscell(varargin{iarg})
    151151        descr=varargin{iarg};
     
    184184    iarg=iarg+2;
    185185end
    186    
     186
    187187if     ~exist('nplotr','var') && ~exist('nplotc','var')
    188188    nplotr=ceil(sqrt(size(sampr,2)));
     
    208208        z(ixi(i),iyi(i))=sampr(i,iresp);
    209209    end
    210    
     210
    211211%  initialize the subplot
    212212
  • issm/trunk/src/m/qmu/plot/plot_sampdist_bars.m

    r7398 r13975  
    7272    dresp=varargin{iarg};
    7373    iarg=iarg+1;
    74    
     74
    7575%     if iarg <= nargin && (iscell(varargin{iarg}) || ischar(varargin{iarg}))
    7676    if iarg <= nargin && iscell(varargin{iarg})
     
    8181    sampr=varargin{iarg};
    8282    iarg=iarg+1;
    83    
     83
    8484    if     iarg <= nargin && iscell(varargin{iarg})
    8585        descr=varargin{iarg};
     
    9191        descr=cell(1:size(sampr,2));
    9292    end
    93    
     93
    9494    dresp=struct([]);
    9595    for i=1:size(sampr,2)
  • issm/trunk/src/m/qmu/process_qmu_options.m

    r8987 r13975  
    9999outoptions.iparams=iparams;
    100100outoptions.runmpi=runmpi;
    101 
  • issm/trunk/src/m/qmu/process_qmu_response_data.m

    r9742 r13975  
    55%
    66% See also PREQMU, PRESOLVE
    7 
    87
    98%preliminary data
     
    2221end
    2322
    24 
    2523%deal with mass flux profiles
    2624if process_mass_flux_profiles,
     
    3028                error('process_qmu_response_data error message: could not find a mass_flux exp profile!');
    3129        end
    32        
     30
    3331        if ~iscell(md.qmu.mass_flux_profiles),
    3432                error('process_qmu_response_data error message: qmu_mass_flux_profiles field should be a cell array of domain outline names');
  • issm/trunk/src/m/qmu/qmu_correlation.m

    r9650 r13975  
    1212        error('qmu_correlation error message: could not find dresp_dat field in dakota results. you need to run montecarlo before computing correlations');
    1313end
    14        
     14
    1515data=md.qmu.results.dresp_dat;
    1616
  • issm/trunk/src/m/qmu/qmuisdistributed.m

    r5200 r13975  
    11function found=qmuisdistribted(string)
    22%QMUISDISTRIBTED - figure out if a string is a decriptor with a numerical postfix. Like thickness1, or drag10
    3 
    43
    54%just take last string element, and see if it is numeric.
  • issm/trunk/src/m/qmu/qmumarshall.m

    r9650 r13975  
    4747        end
    4848end
    49                        
     49
    5050if qmu_segments,
    5151        WriteData(fid,md.qmu.mass_flux_num_profiles,'Integer','qmu_mass_flux_num_profiles');
     
    5757        WriteData(fid,md.qmu.mass_flux_num_profiles,'Integer','qmu_mass_flux_num_profiles');
    5858end
    59 
    6059
    6160%write part and npart to disk
     
    7170end
    7271
    73 function qmumarshallusage();
     72function qmumarshallusage()
    7473disp(' ');
    7574disp('function qmumarshall(md.qmu.variables,responses)');
  • issm/trunk/src/m/qmu/qmuresponse.m

    r4431 r13975  
    114114        error(['qmuresponse error message: unknown descriptor ' descriptor]);
    115115end
    116 
  • issm/trunk/src/m/qmu/qmuroot.m

    r2157 r13975  
    1111        end
    1212end
    13 
  • issm/trunk/src/m/qmu/rlist_write.m

    r13395 r13975  
    6868
    6969end
    70 
  • issm/trunk/src/m/qmu/sensitivities.m

    r13395 r13975  
    88%   Example: sens=sensitivities(md,'DragCoefficient','MaxVel');
    99%
    10 
    1110
    1211variablenamelength=length(variablename);
  • issm/trunk/src/m/qmu/setupdesign/IsScaled.m

    r9742 r13975  
    1212
    1313case {'RiftsFriction'},
    14        
     14
    1515        status=2; %special treatment
    1616
  • issm/trunk/src/m/qmu/setupdesign/QmuSetupVariables.m

    r9650 r13975  
    66%decide whether this is a distributed variable, which will drive whether we expand it into npart values,
    77%or if we just carry it forward as is.
    8 
    98
    109%ok, key off according to type of descriptor:
  • issm/trunk/src/m/qmu/vector_write.m

    r13395 r13975  
    3131    nitem=nitem+1;
    3232    lsvec=lsvec+1+length(sitem);
    33    
     33
    3434    if (nitem <= nmax) && (lsvec <= cmax)
    3535        svec=[svec ' ' sitem];
  • issm/trunk/src/m/regional/BasinConstrain.m

    r13395 r13975  
    1 function md=BasinConstrain(md,domain);
     1function md=BasinConstrain(md,domain)
    22%BASINCONSTRAIN - constrain basin
    33%
  • issm/trunk/src/m/regional/BasinConstrainShelf.m

    r13395 r13975  
    1 function md=BasinConstrainShelf(md,domain);
     1function md=BasinConstrainShelf(md,domain)
    22%BASINCONSTRAIN - constrain basin
    33%
  • issm/trunk/src/m/regional/basinzoom.m

    r13395 r13975  
    3939%Ok, find basin we are talking about:
    4040load([jplsvn() '/projects/ModelData/Names/Names.mat']);
    41                
     41
    4242%Go through names:
    4343found=0;
  • issm/trunk/src/m/regional/regionaltransient2d.m

    r13395 r13975  
    3131
    3232%take every fields from model
    33 mde=modelextract(md1,area);
     33mde=md1.extract(area);
    3434mde.private.bamg=[];
    3535mde.mesh.extractedvertices=nan;
     
    131131        %Diagnostic.  Don't spc the icefront vertices.
    132132        if ~isnan(md2.diagnostic.icefront)
    133                 md1s=modelextract(md1,area);
     133                md1s=md1.extract(area);
    134134                %md2.diagnostic.icefront=[md2.mesh.segments 2];
    135135                e2=md2.mesh.segments(:,end);
     
    156156                md2.results=[];
    157157        end
    158 
  • issm/trunk/src/m/regional/showbasins.m

    r13395 r13975  
    2121        options=pairoptions(varargin{:});
    2222end
    23 
    2423
    2524%recover some options, and set defaults
  • issm/trunk/src/m/solve/MatlabProcessPatch.m

    r13395 r13975  
    1 function structure=MatlabProcessPatch(structure);
     1function structure=MatlabProcessPatch(structure)
    22%PROCESSPATCH - create a structure from a patch
    33%
  • issm/trunk/src/m/solve/MatlabProcessPatch.py

    r13395 r13975  
    88
    99        #loop over steps
    10         for structurei in structure.itervalues():
     10        for structurei in structure:
    1111
    1212                #return if there is no field Patch
    13                 if 'Patch' not in structurei:
     13                if not hasattr(structurei,'Patch'):
    1414                        continue
    1515
  • issm/trunk/src/m/solve/WriteData.m

    r13395 r13975  
    231231
    232232        %Get Enum
    233         enum=eval([string 'Enum();']);
     233        enum=StringToEnum(string);
    234234end % }}}
    235235function code=FormatToCode(format) % {{{
  • issm/trunk/src/m/solve/WriteData.py

    r13395 r13975  
    1717        #process options
    1818        #  the import above the function level doesn't work?
    19         from pairoptions import *
     19        from pairoptions import pairoptions
    2020        options=pairoptions(*args)
    2121
     
    101101        elif strcmpi(format,'BooleanMat'):    # {{{
    102102
    103                 if isinstance(data,bool):
     103                if   isinstance(data,bool):
    104104                        data=numpy.array([data])
     105                elif isinstance(data,(list,tuple)):
     106                        data=numpy.array(data).reshape(-1,1)
    105107                if len(data.shape) == 1:
    106108                        if numpy.size(data):
     
    132134        elif strcmpi(format,'IntMat'):    # {{{
    133135
    134                 if isinstance(data,(int,long)):
     136                if   isinstance(data,(int,long)):
    135137                        data=numpy.array([data])
     138                elif isinstance(data,(list,tuple)):
     139                        data=numpy.array(data).reshape(-1,1)
    136140                if len(data.shape) == 1:
    137141                        if numpy.size(data):
     
    163167        elif strcmpi(format,'DoubleMat'):    # {{{
    164168
    165                 if isinstance(data,(bool,int,long,float)):
     169                if   isinstance(data,(bool,int,long,float)):
    166170                        data=numpy.array([data])
     171                elif isinstance(data,(list,tuple)):
     172                        data=numpy.array(data).reshape(-1,1)
    167173                if len(data.shape) == 1:
    168174                        if numpy.size(data):
     
    197203                recordlength=4+4    #number of records + code
    198204                for matrix in data:
    199                         if isinstance(matrix,(bool,int,long,float)):
     205                        if   isinstance(matrix,(bool,int,long,float)):
    200206                                matrix=numpy.array([matrix])
     207                        elif isinstance(matrix,(list,tuple)):
     208                                matrix=numpy.array(matrix).reshape(-1,1)
    201209                        if len(matrix.shape) == 1:
    202210                                if numpy.size(matrix):
     
    219227                #write each matrix:
    220228                for matrix in data:
    221                         if isinstance(matrix,(bool,int,long,float)):
     229                        if   isinstance(matrix,(bool,int,long,float)):
    222230                                matrix=numpy.array([matrix])
     231                        elif isinstance(matrix,(list,tuple)):
     232                                matrix=numpy.array(matrix).reshape(-1,1)
    223233                        if len(matrix.shape) == 1:
    224234                                matrix=matrix.reshape(numpy.size(matrix),1)
     
    276286
    277287        #Get Enum
    278         exec('enum='+string+'Enum()',globals())
     288        enum=StringToEnum(string)[0]
    279289
    280290        return enum
  • issm/trunk/src/m/solve/loadresultsfromdisk.m

    r13395 r13975  
    5050        end
    5151
    52 
    5352%post processes qmu results if necessary
    5453else
  • issm/trunk/src/m/solve/loadresultsfromdisk.py

    r13395 r13975  
    11import os
    2 from collections import OrderedDict
     2from results import *
    33from parseresultsfromdisk import *
    44from EnumToString import EnumToString
     5from MatlabFuncs import *
    56
    67def loadresultsfromdisk(md,filename):
     
    2324
    2425                #initialize md.results if not a structure yet
    25                 if not isinstance(md.results,dict):
    26                         md.results=OrderedDict()
     26                if not isinstance(md.results,results):
     27                        md.results=results()
    2728
    2829                #load results onto model
    29                 structure=parseresultsfromdisk(filename,~md.settings.io_gather)
     30                structure=parseresultsfromdisk(filename,not md.settings.io_gather)
    3031                if not len(structure):
    3132                        raise RuntimeError("No result found in binary file '%s'. Check for solution crash." % filename)
    32                 md.results[structure[1]['SolutionType']]=structure;
     33                setattr(md.results,structure[0].SolutionType,structure)
    3334
    3435                #recover solution_type from results
    35                 md.private.solution=structure[1]['SolutionType']
     36                md.private.solution=structure[0].SolutionType
    3637
    3738                #read log files onto fields
    3839                if os.path.exists(md.miscellaneous.name+'.errlog'):
    3940                        with open(md.miscellaneous.name+'.errlog','r') as f:
    40                                 md.results[structure[1]['SolutionType']]['errlog']=[line[:-1] for line in f]
     41                                setattr(getattr(md.results,structure[0].SolutionType)[0],'errlog',[line[:-1] for line in f])
    4142                else:
    42                         md.results[structure[1]['SolutionType']]['errlog']=[]
     43                        setattr(getattr(md.results,structure[0].SolutionType)[0],'errlog',[])
    4344
    4445                if os.path.exists(md.miscellaneous.name+'.outlog'):
    4546                        with open(md.miscellaneous.name+'.outlog','r') as f:
    46                                 md.results[structure[1]['SolutionType']]['outlog']=[line[:-1] for line in f]
     47                                setattr(getattr(md.results,structure[0].SolutionType)[0],'outlog',[line[:-1] for line in f])
    4748                else:
    48                         md.results[structure[1]['SolutionType']]['outlog']=[]
     49                        setattr(getattr(md.results,structure[0].SolutionType)[0],'outlog',[])
    4950
    50                 if len(md.results[structure[1]['SolutionType']]['errlog']):
     51                if len(getattr(md.results,structure[0].SolutionType)[0].errlog):
    5152                        print ("loadresultsfromcluster info message: error during solution. Check your errlog and outlog model fields.")
     53
     54                #if only one solution, extract it from list for user friendliness
     55                if len(structure) == 1 and not strcmp(structure[0].SolutionType,'TransientSolution'):
     56                        setattr(md.results,structure[0].SolutionType,structure[0])
    5257
    5358        #post processes qmu results if necessary
  • issm/trunk/src/m/solve/marshall.m

    r13395 r13975  
    3636        %Marshall current object
    3737        %disp(['marshalling ' field '...']);
    38         if verLessThan('matlab', '7.6')
    39                 marshall(md.(field),fid);
    40         else
    41                 md.(field).marshall(fid);
    42         end
     38        marshall(md.(field),fid);
    4339end
    4440
  • issm/trunk/src/m/solve/parseresultsfromdisk.m

    r13395 r13975  
    1919%   Usage:
    2020%      results=parseresultsfromdiskioserial(filename)
    21 
    2221
    2322%Open file
     
    5453%   Usage:
    5554%      results=parseresultsfromdiskiosplit(filename)
    56 
    5755
    5856%Open file
     
    177175%      field=ReadDataDimensions(fid)
    178176
    179 
    180177%read field
    181178[length,count]=fread(fid,1,'int');
  • issm/trunk/src/m/solve/parseresultsfromdisk.py

    r13395 r13975  
    22import numpy
    33from collections import OrderedDict
     4import results as resultsclass
    45from MatlabFuncs import *
    56from MatlabProcessPatch import *
     
    3738                raise IOError("loadresultsfromdisk error message: could not open '%s' for binary reading." % filename)
    3839
    39         results=OrderedDict()
     40        results=[]
    4041
    4142        #Read fields until the end of the file.
    4243        result=ReadData(fid)
    4344        while result:
     45                if result['step'] > len(results):
     46                        for i in xrange(len(results),result['step']-1):
     47                                results.append(None)
     48                        results.append(resultsclass.results())
    4449                #Get time and step
    45                 if result['step'] not in results:
    46                         results[result['step']]=OrderedDict()
    47                         results[result['step']]['step']=result['step']
    48                         results[result['step']]['time']=result['time']
     50                setattr(results[result['step']-1],'step',result['step'])
     51                setattr(results[result['step']-1],'time',result['time'])
    4952       
    5053                #Add result
    51                 if result['step'] in results and \
    52                    result['fieldname'] in results[result['step']] and \
    53                    not strcmp(result['fieldname'],'SolutionType'):
    54                         results[result['step']][result['fieldname']]=numpy.concatenate((results[result['step']][result['fieldname']],result['field']),axis=0)
    55                 else:
    56                         results[result['step']][result['fieldname']]=result['field']
     54                if hasattr(results[result['step']-1],result['fieldname']) and not strcmp(result['fieldname'],'SolutionType'):
     55                        setattr(results[result['step']-1],result['fieldname'],numpy.vstack((getattr(results[result['step']-1],result['fieldname']),result['field'])))
     56                else:
     57                        setattr(results[result['step']-1],result['fieldname'],result['field'])
    5758
    5859                #read next result
     
    7879                raise IOError("loadresultsfromdisk error message: could not open '%s' for binary reading." % filename)
    7980
    80         results=OrderedDict()
     81        results=[]
    8182
    8283        #if we have done split I/O, ie, we have results that are fragmented across patches,
     
    8687
    8788                #Get time and step
    88                 if result['step'] not in results:
    89                         results[result['step']]=OrderedDict()
    90                         results[result['step']]['step']=result['step']
    91                         results[result['step']]['time']=result['time']
     89                if result['step'] > len(results):
     90                        for i in xrange(len(results),result['step']-1):
     91                                results.append(None)
     92                        results.append(resultsclass.results())
     93                setattr(results[result['step']-1],'step',result['step'])
     94                setattr(results[result['step']-1],'time',result['time'])
    9295
    9396                #Add result
    9497                if strcmpi(result['fieldname'],'Patch'):
    95                         results[result['step']][result['fieldname']]=[0,result['N']]
    96                 else:
    97                         results[result['step']][result['fieldname']]=float('NaN')
     98                        setattr(results[result['step']-1],result['fieldname'],[0,result['N']])
     99                else:
     100                        setattr(results[result['step']-1],result['fieldname'],float('NaN'))
    98101
    99102                #read next result
     
    107110                #Add result
    108111                if strcmpi(result['fieldname'],'Patch'):
    109                         patchdimensions=results[result['step']][result['fieldname']]
    110                         results[result['step']][result['fieldname']]=[patchdimensions[0]+result['M'],result['N']]
     112                        patchdimensions=getattr(results[result['step']-1],result['fieldname'])
     113                        setattr(results[result['step']-1],result['fieldname'],[patchdimensions[0]+result['M'],result['N']])
    111114
    112115                #read next result
     
    116119        for result in results.itervalues():
    117120                if 'Patch' in result:
    118                         result['Patch']=numpy.zeros(shape=(result['Patch'][0],result['Patch'][1]),dtype=float)
    119                         result['counter']=0    #use to index into the patch
     121                        setattr(result,'Patch',numpy.zeros((result['Patch'][0],result['Patch'][1])))
     122                        setattr(result,'counter',0)    #use to index into the patch
    120123
    121124        #third pass, this time to read the real information
     
    125128
    126129                #Get time and step
    127                 if result['step'] not in results:
    128                         results[result['step']]=OrderedDict()
    129                         results[result['step']]['step']=result['step']
    130                         results[result['step']]['time']=result['time']
     130                if result['step']> len(results):
     131                        for i in xrange(len(results),result['step']-1):
     132                                results.append(None)
     133                        results.append(resultsclass.results())
     134                setattr(results[result['step']-1],'step',result['step'])
     135                setattr(results[result['step']-1],'time',result['time'])
    131136
    132137                #Add result
    133138                if strcmpi(result['fieldname'],'Patch'):
    134                         counter=results[result['step']]['counter']
     139                        counter=results[result['step']-1].counter
    135140                        counter2=counter+result['field'].shape[0]-1
    136                         results[result['step']][result['fieldname']][counter:counter2,:]=result['field']
    137 
     141                        getattr(results[result['step']-1],result['fieldname'])[counter:counter2,:]=result['field']
    138142                        #increment counter:
    139                         results[result['step']]['counter']=counter2+1
    140                 else:
    141                         results[result['step']][result['fieldname']]=result['field']
     143                        results[result['step']-1].counter=counter2+1
     144                else:
     145                        setattr(results[result['step']-1],result['fieldname'],result['field'])
    142146
    143147                #read next result
     
    188192
    189193        except struct.error as e:
    190                 result=OrderedDict()
     194                result=None
    191195
    192196        return result
     
    230234
    231235        except struct.error as e:
    232                 result=OrderedDict()
     236                result=None
    233237
    234238        return result
  • issm/trunk/src/m/solve/solve.m

    r13395 r13975  
    7474end
    7575
    76 
    7776%Write all input files
    7877marshall(md);                                          % bin file
    7978PetscFile(md.solver,[md.miscellaneous.name '.petsc']); % petsc file
    8079BuildQueueScript(cluster,md.private.runtimename,md.miscellaneous.name,md.private.solution,md.settings.io_gather,md.debug.valgrind,md.debug.gprof); % queue file
    81 
    8280
    8381%Stop here if batch mode
  • issm/trunk/src/m/solve/waitonlock.m

    r13395 r13975  
    1212cluster=md.cluster.name;
    1313login=md.cluster.login;
    14 port=md.cluster.port;
     14if isprop(md.cluster,'port')
     15        port=md.cluster.port;
     16end
    1517timelimit=md.settings.waitonlock;
    1618filename=[executionpath '/' md.private.runtimename '/' md.miscellaneous.name '.lock'];
  • issm/trunk/src/m/solvers/asmoptions.m

    r13395 r13975  
    44%   Usage:
    55%      options=asmoptions;
    6                          
     6
    77%retrieve options provided in varargin
    88options=pairoptions(varargin{:});
  • issm/trunk/src/m/solvers/iluasmoptions.m

    r13395 r13975  
    44%   Usage:
    55%      options=iluasmoptions;
    6                          
     6
    77%retrieve options provided in varargin
    88options=pairoptions(varargin{:});
  • issm/trunk/src/m/solvers/jacobiasmoptions.m

    r13395 r13975  
    44%   Usage:
    55%      options=jacobiasmoptions;
    6                          
     6
    77%retrieve options provided in varargin
    88options=pairoptions(varargin{:});
  • issm/trunk/src/m/solvers/jacobicgoptions.m

    r13395 r13975  
    44%   Usage:
    55%      options=jacobiasmoptions;
    6                          
     6
    77%retrieve options provided in varargin
    88options=pairoptions(varargin{:});
  • issm/trunk/src/m/solvers/matlaboptions.m

    r13395 r13975  
    44%   Usage:
    55%      options=matlaboptions;
    6                          
     6
    77%retrieve options provided in varargin
    88options=pairoptions(varargin{:});
  • issm/trunk/src/m/solvers/soroptions.m

    r13395 r13975  
    44%   Usage:
    55%      options=soroptions;
    6                          
     6
    77%retrieve options provided in varargin
    88options=pairoptions(varargin{:});
  • issm/trunk/src/m/string/issmprintf.m

    r13395 r13975  
    88%   Example:
    99%      issmprintf(1,'%s\n','string to display');
    10        
     10
    1111if flag,
    1212        disp(sprintf(format,varargin{:}));
  • issm/trunk/src/m/string/strsplit.m

    r13395 r13975  
    1616
    1717%   mailto:    gie.spaepen@ua.ac.be
    18 
    19 
    2018
    2119%Check input arguments
     
    8785        splittedstring = tempsplit;
    8886    end
    89    
    90        
     87
    9188end
  • issm/trunk/src/m/string/strsplit_strict.m

    r13395 r13975  
    44%   Usage:
    55%      output = strsplit_strict(inpstr,delimiter)
    6 
    76
    87%Check input arguments
Note: See TracChangeset for help on using the changeset viewer.