Changeset 27035 for issm/trunk/src


Ignore:
Timestamp:
06/01/22 05:01:48 (3 years ago)
Author:
Mathieu Morlighem
Message:

merged trunk-jpl and trunk for revision 27033

Location:
issm/trunk
Files:
3 deleted
215 edited
17 copied

Legend:

Unmodified
Added
Removed
  • issm/trunk

  • issm/trunk/src

  • issm/trunk/src/c/Makefile.am

    r26744 r27035  
    1 AM_CPPFLAGS = @NEOPZINCL@ @DAKOTAINCL@ @SHAPELIBINCL@ @TRIANGLEINCL@ @PETSCINCL@ @SLEPCINCL@ @AMPIINCL@ @ADJOINTMPIINCL@ @MEDIPACKINCL@ @MPIINCL@ @PARMETISINCL@ @METISINCL@ @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@ @MKLINCL@ @MUMPSINCL@ @SPAIINCL@ @HYPREINCL@ @PROMETHEUSINCL@ @SUPERLUINCL@ @SPOOLESINCL@ @PASTIXINCL@ @MLINCL@ @TAOINCL@ @ADIC2INCL@ @ADOLCINCL@ @CODIPACKINCL@ @GSLINCL@ @BOOSTINCL@ @ANDROID_NDKINCL@ @METEOIOINCL@ @SNOWPACKINCL@ @PROJINCL@ @ESMFINCL@ @PROJINCL@
     1AM_CPPFLAGS = @NEOPZINCL@ @DAKOTAINCL@ @SHAPELIBINCL@ @TRIANGLEINCL@ @PETSCINCL@ @SLEPCINCL@ @AMPIINCL@ @ADJOINTMPIINCL@ @MEDIPACKINCL@ @MPIINCL@ @PARMETISINCL@ @METISINCL@ @CHACOINCL@ @SCOTCHINCL@ @PLAPACKINCL@ @MKLINCL@ @MUMPSINCL@ @SPAIINCL@ @HYPREINCL@ @PROMETHEUSINCL@ @SUPERLUINCL@ @SPOOLESINCL@ @PASTIXINCL@ @MLINCL@ @TAOINCL@ @ADIC2INCL@ @ADOLCINCL@ @CODIPACKINCL@ @GSLINCL@ @BOOSTINCL@ @ANDROID_NDKINCL@ @METEOIOINCL@ @SNOWPACKINCL@ @PROJINCL@ @ESMFINCL@ @PROJINCL@ @MPLAPACKINCL@
    22AM_FCFLAGS = @SEMICINCL@
    33
     
    273273        ./classes/RiftStruct.cpp \
    274274        ./modules/ModelProcessorx/Transient/UpdateElementsTransient.cpp \
     275        ./modules/ModelProcessorx/Transient/UpdateParametersTransient.cpp \
    275276        ./cores/transient_core.cpp \
    276277        ./cores/steadystate_core.cpp \
     
    714715if !WINDOWS
    715716if !STANDALONE_LIBRARIES
    716 libISSMCore_la_LIBADD = $(CHACOLIB) $(DAKOTALIB) $(PETSCLIB) $(MUMPSLIB) $(SCALAPACKLIB) $(BLASLAPACKLIB) $(PARMETISLIB) $(METISLIB) $(HDF5LIB) $(TAOLIB) $(M1QN3LIB) $(SEMICLIB) $(PLAPACKLIB) $(SUPERLULIB) $(SPOOLESLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(SCOTCHLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(ADOLCLIB) $(AMPILIB) $(ADJOINTMPILIB) $(METEOIOLIB) $(SNOWPACKLIB) $(PROJLIB) $(OSLIBS)
     717libISSMCore_la_LIBADD = $(CHACOLIB) $(DAKOTALIB) $(PETSCLIB) $(MUMPSLIB) $(SCALAPACKLIB) $(BLASLAPACKLIB) $(PARMETISLIB) $(METISLIB) $(HDF5LIB) $(TAOLIB) $(M1QN3LIB) $(SEMICLIB) $(PLAPACKLIB) $(MPLAPACKLIB) $(SUPERLULIB) $(SPOOLESLIB) $(BLACSLIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(SCOTCHLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(ADOLCLIB) $(AMPILIB) $(ADJOINTMPILIB) $(METEOIOLIB) $(SNOWPACKLIB) $(PROJLIB) $(OSLIBS)
    717718if FORTRAN
    718719libISSMCore_la_LIBADD += $(FLIBS) $(FORTRANLIB)
     
    830831
    831832# External packages
    832 LDADD += $(CHACOLIB) $(DAKOTALIB) $(PETSCLIB) $(MUMPSLIB) $(SCALAPACKLIB) $(BLASLAPACKLIB) $(PARMETISLIB) $(METISLIB) $(NEOPZLIB) $(TAOLIB) $(M1QN3LIB) $(SEMICLIB) $(PLAPACKLIB) $(SUPERLULIB) $(SPOOLESLIB) $(BLACSLIB) $(HDF5LIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(SCOTCHLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(AMPILIB) $(ADJOINTMPILIB) $(ADOLCLIB) $(MPILIB) $(METEOIOLIB) $(SNOWPACKLIB) $(PROJLIB) $(ESMFLIB) $(OSLIBS)
     833LDADD += $(CHACOLIB) $(DAKOTALIB) $(PETSCLIB) $(MUMPSLIB) $(SCALAPACKLIB) $(BLASLAPACKLIB) $(PARMETISLIB) $(METISLIB) $(NEOPZLIB) $(TAOLIB) $(M1QN3LIB) $(SEMICLIB) $(PLAPACKLIB) $(MPLAPACKLIB) $(SUPERLULIB) $(SPOOLESLIB) $(BLACSLIB) $(HDF5LIB) $(HYPRELIB) $(SPAILIB) $(PROMETHEUSLIB) $(PASTIXLIB) $(MLLIB) $(SCOTCHLIB) $(MKLLIB) $(MPILIB) $(MATHLIB) $(GRAPHICSLIB) $(MULTITHREADINGLIB) $(GSLLIB) $(AMPILIB) $(ADJOINTMPILIB) $(ADOLCLIB) $(MPILIB) $(METEOIOLIB) $(SNOWPACKLIB) $(PROJLIB) $(ESMFLIB) $(OSLIBS)
    833834
    834835if FORTRAN
  • issm/trunk/src/c/analyses/AdjointHorizAnalysis.cpp

    r26744 r27035  
    5252                case FSApproximationEnum:
    5353                        return CreateKMatrixFS(element);
    54       case MLHOApproximationEnum:
     54      case MOLHOApproximationEnum:
    5555                // a more accurate option, but integrate in the vertical direction numerically.
    56                 //      return CreateKMatrixMLHOVerticalIntergrated(element);
    57                         return CreateKMatrixMLHO(element);
     56                //      return CreateKMatrixMOLHOVerticalIntergrated(element);
     57                        return CreateKMatrixMOLHO(element);
    5858                case NoneApproximationEnum:
    5959                        return NULL;
     
    220220        return Ke;
    221221}/*}}}*/
    222 ElementMatrix* AdjointHorizAnalysis::CreateKMatrixMLHO(Element* element){/*{{{*/
     222ElementMatrix* AdjointHorizAnalysis::CreateKMatrixMOLHO(Element* element){/*{{{*/
    223223
    224224        /* Check if ice in element */
     
    226226
    227227        /*Intermediaries */
    228         bool        incomplete_adjoint;
    229228        IssmDouble  Jdet,mu_prime,n,thickness,mu,effmu;
    230229        IssmDouble *xyz_list = NULL;
     
    238237        IssmDouble  vxshear, vyshear;
    239238
    240    Element* basalelement;
     239   /*Get basal element*/
     240        Element* basalelement = NULL;
     241   element->FindParam(&domaintype,DomainTypeEnum);
     242   switch(domaintype){
     243      case Domain2DhorizontalEnum:
     244         basalelement = element;
     245         break;
     246      case Domain3DEnum: case Domain2DverticalEnum:
     247         _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
     248         break;
     249      default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
     250   }
     251
     252        /*Initialize Jacobian with regular HO (first part of the Gateau derivative)*/
     253        bool        incomplete_adjoint;
     254        element->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
     255        StressbalanceAnalysis* analysis = new StressbalanceAnalysis();
     256        ElementMatrix* Ke=analysis->CreateKMatrix(basalelement);
     257        delete analysis;
     258        if(incomplete_adjoint) return Ke;
     259
     260        /*Second part of the Gateau derivative if requested*/
     261
     262        /*Fetch number of nodes and dof for this finite element*/
     263   int numnodes = basalelement->GetNumberOfNodes();
     264   IssmDouble* dbasis = xNew<IssmDouble>(2*numnodes); // like SSA
     265   IssmDouble* basis  = xNew<IssmDouble>(numnodes); // like SSA
     266
     267        /*Retrieve all inputs and parameters*/
     268        element->GetVerticesCoordinates(&xyz_list);
     269   Input* vx_input       = element->GetInput(VxEnum);        _assert_(vx_input); //vertically integrated vx
     270   Input* vy_input       = element->GetInput(VyEnum);        _assert_(vy_input); //vertically integrated vy
     271   Input* vxbase_input   = element->GetInput(VxBaseEnum);    _assert_(vxbase_input);
     272   Input* vybase_input   = element->GetInput(VyBaseEnum);    _assert_(vybase_input);
     273   Input* vxshear_input  = element->GetInput(VxShearEnum);   _assert_(vxshear_input);
     274   Input* vyshear_input  = element->GetInput(VyShearEnum);   _assert_(vyshear_input);
     275   Input* thickness_input= element->GetInput(ThicknessEnum); _assert_(thickness_input);
     276   Input* n_input        = element->GetInput(MaterialsRheologyNEnum); _assert_(n_input);
     277
     278        /* Start  looping on the number of gaussian points: */
     279   Gauss* gauss      = element->NewGauss(5);
     280   Gauss* gauss_base = basalelement->NewGauss();
     281   while(gauss->next()){
     282      gauss->SynchronizeGaussBase(gauss_base);
     283
     284      element->JacobianDeterminant(&Jdet,xyz_list,gauss_base);
     285      basalelement->NodalFunctionsDerivatives(dbasis,xyz_list,gauss_base);
     286      basalelement->NodalFunctions(basis, gauss_base);
     287
     288      thickness_input->GetInputValue(&thickness, gauss);
     289      n_input->GetInputValue(&n,gauss);
     290
     291      vxshear_input->GetInputValue(&vxshear,gauss);
     292      vyshear_input->GetInputValue(&vyshear,gauss);
     293
     294                element->material->ViscosityMOLHOAdjoint(&viscosity[0],dim,xyz_list,gauss,vxbase_input,vybase_input,vxshear_input,vyshear_input,thickness_input,n_input);
     295
     296                effmu = 2.0*(1-n)/2.0/n;
     297
     298                element->StrainRateHO(&epsilonbase[0],xyz_list,gauss,vxbase_input, vybase_input);
     299                element->StrainRateHO(&epsilonshear[0],xyz_list,gauss,vxshear_input, vyshear_input);
     300
     301                e1b[0] = 2*epsilonbase[0]+epsilonbase[1];               e1b[1] = epsilonbase[2];
     302                e2b[1] = epsilonbase[0]+2*epsilonbase[1];               e2b[0] = epsilonbase[2];
     303
     304                e1sh[0] = 2*epsilonshear[0]+epsilonshear[1];            e1sh[1] = epsilonshear[2];
     305                e2sh[1] = epsilonshear[0]+2*epsilonshear[1];            e2sh[0] = epsilonshear[2];
     306
     307                for(int i=0;i<numnodes;i++){
     308                        for(int j=0;j<numnodes;j++){
     309                                eb1i = e1b[0]*dbasis[0*numnodes+i]+e1b[1]*dbasis[1*numnodes+i];
     310                                eb1j = e1b[0]*dbasis[0*numnodes+j]+e1b[1]*dbasis[1*numnodes+j];
     311                                eb2i = e2b[0]*dbasis[0*numnodes+i]+e2b[1]*dbasis[1*numnodes+i];
     312                                eb2j = e2b[0]*dbasis[0*numnodes+j]+e2b[1]*dbasis[1*numnodes+j];
     313            esh1i = e1sh[0]*dbasis[0*numnodes+i]+e1sh[1]*dbasis[1*numnodes+i];
     314            esh1j = e1sh[0]*dbasis[0*numnodes+j]+e1sh[1]*dbasis[1*numnodes+j];
     315            esh2i = e2sh[0]*dbasis[0*numnodes+i]+e2sh[1]*dbasis[1*numnodes+i];
     316            esh2j = e2sh[0]*dbasis[0*numnodes+j]+e2sh[1]*dbasis[1*numnodes+j];
     317
     318                                Ke->values[4*numnodes*(4*i+0)+4*j+0]+=gauss->weight*Jdet*effmu*(viscosity[0]*eb1j*eb1i+viscosity[1]*(esh1j*eb1i+eb1j*esh1i)+viscosity[2]*esh1j*esh1i);
     319                                Ke->values[4*numnodes*(4*i+1)+4*j+0]+=gauss->weight*Jdet*effmu*(viscosity[1]*eb1j*eb1i+viscosity[2]*(esh1j*eb1i+eb1j*esh1i)+viscosity[4]*esh1j*esh1i+viscosity[3]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*eb1j*basis[i]+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*esh1j*basis[i]);
     320                                Ke->values[4*numnodes*(4*i+2)+4*j+0]+=gauss->weight*Jdet*effmu*(viscosity[0]*eb1j*eb2i+viscosity[1]*(esh1j*eb2i+eb1j*esh2i)+viscosity[2]*esh1j*esh2i);
     321                                Ke->values[4*numnodes*(4*i+3)+4*j+0]+=gauss->weight*Jdet*effmu*(viscosity[1]*eb1j*eb2i+viscosity[2]*(esh1j*eb2i+eb1j*esh2i)+viscosity[4]*esh1j*esh2i+viscosity[3]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*eb1j*basis[i]+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*esh1j*basis[i]);
     322
     323                                Ke->values[4*numnodes*(4*i+0)+4*j+1]+=gauss->weight*Jdet*effmu*(viscosity[1]*eb1j*eb1i+viscosity[2]*(esh1j*eb1i+eb1j*esh1i)+viscosity[4]*esh1j*esh1i+viscosity[3]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*eb1i*basis[j]+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*esh1i*basis[j]);
     324                                Ke->values[4*numnodes*(4*i+1)+4*j+1]+=gauss->weight*Jdet*effmu*(viscosity[2]*eb1j*eb1i+viscosity[4]*(esh1j*eb1i+eb1j*esh1i)+viscosity[5]*esh1j*esh1i+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*(eb1i*basis[j]+eb1j*basis[i])+viscosity[7]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*(esh1i*basis[j]+esh1j*basis[i])+viscosity[8]*(n+1)*(n+1)*(n+1)*(n+1)/4.0/thickness/thickness/thickness/thickness*vxshear*vxshear*basis[j]*basis[i]);
     325                                Ke->values[4*numnodes*(4*i+2)+4*j+1]+=gauss->weight*Jdet*effmu*(viscosity[1]*eb1j*eb2i+viscosity[2]*(esh1j*eb2i+eb1j*esh2i)+viscosity[4]*esh1j*esh2i+viscosity[3]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*eb2i*basis[j]+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*esh2i*basis[j]);
     326                                Ke->values[4*numnodes*(4*i+3)+4*j+1]+=gauss->weight*Jdet*effmu*(viscosity[2]*eb1j*eb2i+viscosity[4]*(esh1j*eb2i+eb1j*esh2i)+viscosity[5]*esh1j*esh2i+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*(vxshear*eb2i*basis[j]+vyshear*eb1j*basis[i])+viscosity[7]*(n+1)*(n+1)/2.0/thickness/thickness*(vxshear*esh2i*basis[j]+vyshear*esh1j*basis[i])+viscosity[8]*(n+1)*(n+1)*(n+1)*(n+1)/4.0/thickness/thickness/thickness/thickness*vxshear*vyshear*basis[j]*basis[i]);
     327                               
     328
     329                                Ke->values[4*numnodes*(4*i+0)+4*j+2]+=gauss->weight*Jdet*effmu*(viscosity[0]*eb2j*eb1i+viscosity[1]*(esh2j*eb1i+eb2j*esh1i)+viscosity[2]*esh2j*esh1i);
     330                                Ke->values[4*numnodes*(4*i+1)+4*j+2]+=gauss->weight*Jdet*effmu*(viscosity[1]*eb2j*eb1i+viscosity[2]*(esh2j*eb1i+eb2j*esh1i)+viscosity[4]*esh2j*esh1i+viscosity[3]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*eb2j*basis[i]+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*esh2j*basis[i]);
     331                                Ke->values[4*numnodes*(4*i+2)+4*j+2]+=gauss->weight*Jdet*effmu*(viscosity[0]*eb2j*eb2i+viscosity[1]*(esh2j*eb2i+eb2j*esh2i)+viscosity[2]*esh2j*esh2i);
     332                                Ke->values[4*numnodes*(4*i+3)+4*j+2]+=gauss->weight*Jdet*effmu*(viscosity[1]*eb2j*eb2i+viscosity[2]*(esh2j*eb2i+eb2j*esh2i)+viscosity[4]*esh2j*esh2i+viscosity[3]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*eb2j*basis[i]+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*esh2j*basis[i]);
     333
     334
     335                                Ke->values[4*numnodes*(4*i+0)+4*j+3]+=gauss->weight*Jdet*effmu*(viscosity[1]*eb2j*eb1i+viscosity[2]*(esh2j*eb1i+eb2j*esh1i)+viscosity[4]*esh2j*esh1i+viscosity[3]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*eb1i*basis[j]+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*esh1i*basis[j]);
     336                                Ke->values[4*numnodes*(4*i+1)+4*j+3]+=gauss->weight*Jdet*effmu*(viscosity[2]*eb2j*eb1i+viscosity[4]*(esh2j*eb1i+eb2j*esh1i)+viscosity[5]*esh2j*esh1i+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*(vyshear*eb1i*basis[j]+vxshear*eb2j*basis[i])+viscosity[7]*(n+1)*(n+1)/2.0/thickness/thickness*(vxshear*esh2j*basis[i]+vyshear*esh1i*basis[j])+viscosity[8]*(n+1)*(n+1)*(n+1)*(n+1)/4.0/thickness/thickness/thickness/thickness*vxshear*vxshear*basis[j]*basis[i]);
     337                                Ke->values[4*numnodes*(4*i+2)+4*j+3]+=gauss->weight*Jdet*effmu*(viscosity[1]*eb2j*eb2i+viscosity[2]*(esh2j*eb2i+eb2j*esh2i)+viscosity[4]*esh2j*esh2i+viscosity[3]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*eb2i*basis[j]+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*esh2i*basis[j]);
     338                                Ke->values[4*numnodes*(4*i+3)+4*j+3]+=gauss->weight*Jdet*effmu*(viscosity[2]*eb2j*eb2i+viscosity[4]*(esh2j*eb2i+eb2j*esh2i)+viscosity[5]*esh2j*esh2i+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*(eb2i*basis[j]+eb1j*basis[i])+viscosity[7]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*(esh2i*basis[j]+esh1j*basis[i])+viscosity[8]*(n+1)*(n+1)*(n+1)*(n+1)/4.0/thickness/thickness/thickness/thickness*vyshear*vyshear*basis[j]*basis[i]);
     339                        }
     340                }
     341        }
     342
     343        /*Transform Coordinate System*/
     344        /*element->TransformStiffnessMatrixCoord(Ke,XYEnum);*/
     345
     346   /*Clean up and return*/
     347   delete gauss;
     348   delete gauss_base;
     349   if(basalelement->IsSpawnedElement()){basalelement->DeleteMaterials(); delete basalelement;};
     350   xDelete<IssmDouble>(xyz_list);
     351   xDelete<IssmDouble>(dbasis);
     352   xDelete<IssmDouble>(basis);
     353   return Ke;
     354}/*}}}*/
     355ElementMatrix* AdjointHorizAnalysis::CreateKMatrixMOLHOVerticalIntergrated(Element* element){/*{{{*/
     356
     357        /* Check if ice in element */
     358        if(!element->IsIceInElement()) return NULL;
     359
     360        /*Intermediaries */
     361        IssmDouble  Jdet,mu_prime,n,thickness,mu,effmu;
     362        IssmDouble *xyz_list = NULL;
     363        IssmDouble      zeta, epsilon_eff;
     364   int                  domaintype;
     365        int                     dim=2;
     366
     367        IssmDouble  e1phi1i, e1phi1j, e2phi1i, e2phi1j, e1phi2i, e1phi2j, e2phi2i, e2phi2j;
     368        IssmDouble  epsilon[5];/* epsilon=[exx,eyy,exy,exz,eyz];*/
     369        IssmDouble      e1[3],e2[3];
     370
     371   Element* basalelement = NULL;
    241372
    242373   /*Get basal element*/
     
    251382      default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
    252383   }
    253         /*Fetch number of nodes and dof for this finite element*/
    254    int numnodes = basalelement->GetNumberOfNodes();
    255    IssmDouble* dbasis = xNew<IssmDouble>(2*numnodes); // like SSA
    256    IssmDouble* basis  = xNew<IssmDouble>(numnodes); // like SSA
    257384
    258385        /*Initialize Jacobian with regular HO (first part of the Gateau derivative)*/
     386        bool incomplete_adjoint;
    259387        element->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
    260388        StressbalanceAnalysis* analysis = new StressbalanceAnalysis();
     
    263391        if(incomplete_adjoint) return Ke;
    264392
    265         /*Retrieve all inputs and parameters*/
    266         element->GetVerticesCoordinates(&xyz_list);
    267    Input* vx_input       = element->GetInput(VxEnum);        _assert_(vx_input); //vertically integrated vx
    268    Input* vy_input       = element->GetInput(VyEnum);        _assert_(vy_input); //vertically integrated vy
    269    Input* vxbase_input   = element->GetInput(VxBaseEnum);    _assert_(vxbase_input);
    270    Input* vybase_input   = element->GetInput(VyBaseEnum);    _assert_(vybase_input);
    271    Input* vxshear_input  = element->GetInput(VxShearEnum);   _assert_(vxshear_input);
    272    Input* vyshear_input  = element->GetInput(VyShearEnum);   _assert_(vyshear_input);
    273    Input* thickness_input= element->GetInput(ThicknessEnum); _assert_(thickness_input);
    274    Input* n_input        = element->GetInput(MaterialsRheologyNEnum); _assert_(n_input);
    275 
    276         /* Start  looping on the number of gaussian points: */
    277    Gauss* gauss      = element->NewGauss(5);
    278    Gauss* gauss_base = basalelement->NewGauss();
    279    while(gauss->next()){
    280       gauss->SynchronizeGaussBase(gauss_base);
    281 
    282       element->JacobianDeterminant(&Jdet,xyz_list,gauss_base);
    283       basalelement->NodalFunctionsDerivatives(dbasis,xyz_list,gauss_base);
    284       basalelement->NodalFunctions(basis, gauss_base);
    285 
    286       thickness_input->GetInputValue(&thickness, gauss);
    287       n_input->GetInputValue(&n,gauss);
    288 
    289       vxshear_input->GetInputValue(&vxshear,gauss);
    290       vyshear_input->GetInputValue(&vyshear,gauss);
    291 
    292                 element->material->ViscosityMLHOAdjoint(&viscosity[0],dim,xyz_list,gauss,vxbase_input,vybase_input,vxshear_input,vyshear_input,thickness_input,n_input);
    293 
    294                 effmu = 2.0*(1-n)/2.0/n;
    295 
    296                 element->StrainRateHO(&epsilonbase[0],xyz_list,gauss,vxbase_input, vybase_input);
    297                 element->StrainRateHO(&epsilonshear[0],xyz_list,gauss,vxshear_input, vyshear_input);
    298 
    299                 e1b[0] = 2*epsilonbase[0]+epsilonbase[1];               e1b[1] = epsilonbase[2];
    300                 e2b[1] = epsilonbase[0]+2*epsilonbase[1];               e2b[0] = epsilonbase[2];
    301 
    302                 e1sh[0] = 2*epsilonshear[0]+epsilonshear[1];            e1sh[1] = epsilonshear[2];
    303                 e2sh[1] = epsilonshear[0]+2*epsilonshear[1];            e2sh[0] = epsilonshear[2];
    304 
    305                 for(int i=0;i<numnodes;i++){
    306                         for(int j=0;j<numnodes;j++){
    307                                 eb1i = e1b[0]*dbasis[0*numnodes+i]+e1b[1]*dbasis[1*numnodes+i];
    308                                 eb1j = e1b[0]*dbasis[0*numnodes+j]+e1b[1]*dbasis[1*numnodes+j];
    309                                 eb2i = e2b[0]*dbasis[0*numnodes+i]+e2b[1]*dbasis[1*numnodes+i];
    310                                 eb2j = e2b[0]*dbasis[0*numnodes+j]+e2b[1]*dbasis[1*numnodes+j];
    311             esh1i = e1sh[0]*dbasis[0*numnodes+i]+e1sh[1]*dbasis[1*numnodes+i];
    312             esh1j = e1sh[0]*dbasis[0*numnodes+j]+e1sh[1]*dbasis[1*numnodes+j];
    313             esh2i = e2sh[0]*dbasis[0*numnodes+i]+e2sh[1]*dbasis[1*numnodes+i];
    314             esh2j = e2sh[0]*dbasis[0*numnodes+j]+e2sh[1]*dbasis[1*numnodes+j];
    315 
    316                                 Ke->values[4*numnodes*(4*i+0)+4*j+0]+=gauss->weight*Jdet*effmu*(viscosity[0]*eb1j*eb1i+viscosity[1]*(esh1j*eb1i+eb1j*esh1i)+viscosity[2]*esh1j*esh1i);
    317                                 Ke->values[4*numnodes*(4*i+1)+4*j+0]+=gauss->weight*Jdet*effmu*(viscosity[1]*eb1j*eb1i+viscosity[2]*(esh1j*eb1i+eb1j*esh1i)+viscosity[4]*esh1j*esh1i+viscosity[3]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*eb1j*basis[i]+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*esh1j*basis[i]);
    318                                 Ke->values[4*numnodes*(4*i+2)+4*j+0]+=gauss->weight*Jdet*effmu*(viscosity[0]*eb1j*eb2i+viscosity[1]*(esh1j*eb2i+eb1j*esh2i)+viscosity[2]*esh1j*esh2i);
    319                                 Ke->values[4*numnodes*(4*i+3)+4*j+0]+=gauss->weight*Jdet*effmu*(viscosity[1]*eb1j*eb2i+viscosity[2]*(esh1j*eb2i+eb1j*esh2i)+viscosity[4]*esh1j*esh2i+viscosity[3]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*eb1j*basis[i]+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*esh1j*basis[i]);
    320 
    321                                 Ke->values[4*numnodes*(4*i+0)+4*j+1]+=gauss->weight*Jdet*effmu*(viscosity[1]*eb1j*eb1i+viscosity[2]*(esh1j*eb1i+eb1j*esh1i)+viscosity[4]*esh1j*esh1i+viscosity[3]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*eb1i*basis[j]+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*esh1i*basis[j]);
    322                                 Ke->values[4*numnodes*(4*i+1)+4*j+1]+=gauss->weight*Jdet*effmu*(viscosity[2]*eb1j*eb1i+viscosity[4]*(esh1j*eb1i+eb1j*esh1i)+viscosity[5]*esh1j*esh1i+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*(eb1i*basis[j]+eb1j*basis[i])+viscosity[7]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*(esh1i*basis[j]+esh1j*basis[i])+viscosity[8]*(n+1)*(n+1)*(n+1)*(n+1)/4.0/thickness/thickness/thickness/thickness*vxshear*vxshear*basis[j]*basis[i]);
    323                                 Ke->values[4*numnodes*(4*i+2)+4*j+1]+=gauss->weight*Jdet*effmu*(viscosity[1]*eb1j*eb2i+viscosity[2]*(esh1j*eb2i+eb1j*esh2i)+viscosity[4]*esh1j*esh2i+viscosity[3]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*eb2i*basis[j]+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*esh2i*basis[j]);
    324                                 Ke->values[4*numnodes*(4*i+3)+4*j+1]+=gauss->weight*Jdet*effmu*(viscosity[2]*eb1j*eb2i+viscosity[4]*(esh1j*eb2i+eb1j*esh2i)+viscosity[5]*esh1j*esh2i+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*(vxshear*eb2i*basis[j]+vyshear*eb1j*basis[i])+viscosity[7]*(n+1)*(n+1)/2.0/thickness/thickness*(vxshear*esh2i*basis[j]+vyshear*esh1j*basis[i])+viscosity[8]*(n+1)*(n+1)*(n+1)*(n+1)/4.0/thickness/thickness/thickness/thickness*vxshear*vyshear*basis[j]*basis[i]);
    325                                
    326 
    327                                 Ke->values[4*numnodes*(4*i+0)+4*j+2]+=gauss->weight*Jdet*effmu*(viscosity[0]*eb2j*eb1i+viscosity[1]*(esh2j*eb1i+eb2j*esh1i)+viscosity[2]*esh2j*esh1i);
    328                                 Ke->values[4*numnodes*(4*i+1)+4*j+2]+=gauss->weight*Jdet*effmu*(viscosity[1]*eb2j*eb1i+viscosity[2]*(esh2j*eb1i+eb2j*esh1i)+viscosity[4]*esh2j*esh1i+viscosity[3]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*eb2j*basis[i]+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vxshear*esh2j*basis[i]);
    329                                 Ke->values[4*numnodes*(4*i+2)+4*j+2]+=gauss->weight*Jdet*effmu*(viscosity[0]*eb2j*eb2i+viscosity[1]*(esh2j*eb2i+eb2j*esh2i)+viscosity[2]*esh2j*esh2i);
    330                                 Ke->values[4*numnodes*(4*i+3)+4*j+2]+=gauss->weight*Jdet*effmu*(viscosity[1]*eb2j*eb2i+viscosity[2]*(esh2j*eb2i+eb2j*esh2i)+viscosity[4]*esh2j*esh2i+viscosity[3]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*eb2j*basis[i]+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*esh2j*basis[i]);
    331 
    332 
    333                                 Ke->values[4*numnodes*(4*i+0)+4*j+3]+=gauss->weight*Jdet*effmu*(viscosity[1]*eb2j*eb1i+viscosity[2]*(esh2j*eb1i+eb2j*esh1i)+viscosity[4]*esh2j*esh1i+viscosity[3]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*eb1i*basis[j]+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*esh1i*basis[j]);
    334                                 Ke->values[4*numnodes*(4*i+1)+4*j+3]+=gauss->weight*Jdet*effmu*(viscosity[2]*eb2j*eb1i+viscosity[4]*(esh2j*eb1i+eb2j*esh1i)+viscosity[5]*esh2j*esh1i+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*(vyshear*eb1i*basis[j]+vxshear*eb2j*basis[i])+viscosity[7]*(n+1)*(n+1)/2.0/thickness/thickness*(vxshear*esh2j*basis[i]+vyshear*esh1i*basis[j])+viscosity[8]*(n+1)*(n+1)*(n+1)*(n+1)/4.0/thickness/thickness/thickness/thickness*vxshear*vxshear*basis[j]*basis[i]);
    335                                 Ke->values[4*numnodes*(4*i+2)+4*j+3]+=gauss->weight*Jdet*effmu*(viscosity[1]*eb2j*eb2i+viscosity[2]*(esh2j*eb2i+eb2j*esh2i)+viscosity[4]*esh2j*esh2i+viscosity[3]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*eb2i*basis[j]+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*esh2i*basis[j]);
    336                                 Ke->values[4*numnodes*(4*i+3)+4*j+3]+=gauss->weight*Jdet*effmu*(viscosity[2]*eb2j*eb2i+viscosity[4]*(esh2j*eb2i+eb2j*esh2i)+viscosity[5]*esh2j*esh2i+viscosity[6]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*(eb2i*basis[j]+eb1j*basis[i])+viscosity[7]*(n+1)*(n+1)/2.0/thickness/thickness*vyshear*(esh2i*basis[j]+esh1j*basis[i])+viscosity[8]*(n+1)*(n+1)*(n+1)*(n+1)/4.0/thickness/thickness/thickness/thickness*vyshear*vyshear*basis[j]*basis[i]);
    337                         }
    338                 }
    339         }
    340 
    341         /*Transform Coordinate System*/
    342         /*element->TransformStiffnessMatrixCoord(Ke,XYEnum);*/
    343 
    344    /*Clean up and return*/
    345    delete gauss;
    346    delete gauss_base;
    347    if(basalelement->IsSpawnedElement()){basalelement->DeleteMaterials(); delete basalelement;};
    348    xDelete<IssmDouble>(xyz_list);
    349    xDelete<IssmDouble>(dbasis);
    350    xDelete<IssmDouble>(basis);
    351    return Ke;
    352 }/*}}}*/
    353 ElementMatrix* AdjointHorizAnalysis::CreateKMatrixMLHOVerticalIntergrated(Element* element){/*{{{*/
    354 
    355         /* Check if ice in element */
    356         if(!element->IsIceInElement()) return NULL;
    357 
    358         /*Intermediaries */
    359         bool        incomplete_adjoint;
    360         IssmDouble  Jdet,mu_prime,n,thickness,mu,effmu;
    361         IssmDouble *xyz_list = NULL;
    362         IssmDouble      zeta, epsilon_eff;
    363    int                  domaintype;
    364         int                     dim=2;
    365 
    366         IssmDouble  e1phi1i, e1phi1j, e2phi1i, e2phi1j, e1phi2i, e1phi2j, e2phi2i, e2phi2j;
    367         IssmDouble  epsilon[5];/* epsilon=[exx,eyy,exy,exz,eyz];*/
    368         IssmDouble      e1[3],e2[3];
    369 
    370    Element* basalelement;
    371 
    372    /*Get basal element*/
    373    element->FindParam(&domaintype,DomainTypeEnum);
    374    switch(domaintype){
    375       case Domain2DhorizontalEnum:
    376          basalelement = element;
    377          break;
    378       case Domain3DEnum: case Domain2DverticalEnum:
    379          _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
    380          break;
    381       default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
    382    }
     393        /*Second part of the Gateau derivative if requested*/
     394
     395
    383396        /*Fetch number of nodes and dof for this finite element*/
    384397   int numnodes = basalelement->GetNumberOfNodes();
    385398   IssmDouble* dbasis = xNew<IssmDouble>(2*numnodes); // like SSA
    386399   IssmDouble* basis  = xNew<IssmDouble>(numnodes); // like SSA
    387 
    388         /*Initialize Jacobian with regular HO (first part of the Gateau derivative)*/
    389         element->FindParam(&incomplete_adjoint,InversionIncompleteAdjointEnum);
    390         StressbalanceAnalysis* analysis = new StressbalanceAnalysis();
    391         ElementMatrix* Ke=analysis->CreateKMatrix(basalelement);
    392         delete analysis;
    393         if(incomplete_adjoint) return Ke;
    394400
    395401        /*Retrieve all inputs and parameters*/
     
    427433
    428434                   /* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy (for a given zeta)*/
    429                         element->StrainRateMLHO(&epsilon[0],xyz_list,gauss,
     435                        element->StrainRateMOLHO(&epsilon[0],xyz_list,gauss,
    430436                  vxbase_input,vybase_input,vxshear_input,vyshear_input,thickness_input,n_input,zeta);
    431437                        epsilon_eff=sqrt(epsilon[0]*epsilon[0] + epsilon[1]*epsilon[1] + epsilon[2]*epsilon[2]
     
    612618                case FSApproximationEnum:
    613619                        return CreatePVectorFS(element);
    614       case MLHOApproximationEnum:
    615                         return CreatePVectorMLHO(element);
     620      case MOLHOApproximationEnum:
     621                        return CreatePVectorMOLHO(element);
    616622                case NoneApproximationEnum:
    617623                        return NULL;
     
    10991105
    11001106}/*}}}*/
    1101 ElementVector* AdjointHorizAnalysis::CreatePVectorMLHO(Element* element){/*{{{*/
     1107ElementVector* AdjointHorizAnalysis::CreatePVectorMOLHO(Element* element){/*{{{*/
    11021108
    11031109        /*Intermediaries*/
     
    11371143
    11381144        /*Initialize Element vector and vectors*/
    1139         ElementVector* pe    = basalelement->NewElementVector(MLHOApproximationEnum);
     1145        ElementVector* pe    = basalelement->NewElementVector(MOLHOApproximationEnum);
    11401146        IssmDouble*    basis = xNew<IssmDouble>(numnodes);
    11411147
     
    12061212                                                }
    12071213                                                else {
    1208                                                         _error_("2D vertical is not implemented for MLHO");
     1214                                                        _error_("2D vertical is not implemented for MOLHO");
    12091215                                                }
    12101216                                        }
     
    12341240                                                }
    12351241                                                else{
    1236                                                         _error_("2D vertical is not implemented for MLHO");
     1242                                                        _error_("2D vertical is not implemented for MOLHO");
    12371243                                                }
    12381244                                        }
     
    12631269                                                }
    12641270                                                else{
    1265                                                         _error_("2D vertical is not implemented for MLHO");
     1271                                                        _error_("2D vertical is not implemented for MOLHO");
    12661272                                                }
    12671273                                        }
     
    12891295                                                }
    12901296                                                else{
    1291                                                         _error_("2D vertical is not implemented for MLHO");
     1297                                                        _error_("2D vertical is not implemented for MOLHO");
    12921298                                                }
    12931299                                        }
     
    13131319                                                }
    13141320                                                else{
    1315                                                         _error_("2D vertical is not implemented for MLHO");
     1321                                                        _error_("2D vertical is not implemented for MOLHO");
    13161322                                                }
    13171323                                        }
     
    16631669                                case L1L2ApproximationEnum:GradientJDragL1L2(element,gradient,control_interp,control_index); break;
    16641670                                case HOApproximationEnum:  GradientJDragHO( element,gradient,control_interp,control_index); break;
    1665                                 case MLHOApproximationEnum:  GradientJDragMLHO( element,gradient,control_interp,control_index); break;
     1671                                case MOLHOApproximationEnum:  GradientJDragMOLHO( element,gradient,control_interp,control_index); break;
    16661672                                case FSApproximationEnum:  GradientJDragFS( element,gradient,control_interp,control_index); break;
    16671673                                case NoneApproximationEnum: /*Gradient is 0*/                    break;
     
    16841690                                case L1L2ApproximationEnum:GradientJBbarL1L2(element,gradient,control_interp,control_index); break;
    16851691                                case HOApproximationEnum:  GradientJBbarHO( element,gradient,control_interp,control_index); break;
    1686                                 case MLHOApproximationEnum:  GradientJBbarMLHO( element,gradient,control_interp,control_index); break;
     1692                                case MOLHOApproximationEnum:  GradientJBbarMOLHO( element,gradient,control_interp,control_index); break;
    16871693                                case FSApproximationEnum:  GradientJBbarFS( element,gradient,control_interp,control_index); break;
    16881694                                case NoneApproximationEnum: /*Gradient is 0*/                    break;
     
    16941700                                case SSAApproximationEnum: GradientJBSSA(element,gradient,control_interp,control_index); break;
    16951701                                case HOApproximationEnum:  GradientJBHO( element,gradient,control_interp,control_index); break;
    1696                         //      case MLHOApproximationEnum:  GradientJBMLHO( element,gradient,control_interp,control_index); break;
     1702                        //      case MOLHOApproximationEnum:  GradientJBMOLHO( element,gradient,control_interp,control_index); break;
    16971703                                case FSApproximationEnum:  GradientJBFS( element,gradient,control_interp,control_index); break;
    16981704                                case NoneApproximationEnum: /*Gradient is 0*/                    break;
     
    18041810        this->GradientJBbarSSA(element,gradient,control_interp,control_index);
    18051811}/*}}}*/
    1806 void           AdjointHorizAnalysis::GradientJBbarMLHO(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index){/*{{{*/
     1812void           AdjointHorizAnalysis::GradientJBbarMOLHO(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index){/*{{{*/
    18071813
    18081814   if(control_interp!=P1Enum) _error_("not implemented yet...");
     
    18871893                        zeta=0.5*(gauss_seg->coord1+1);
    18881894
    1889                         basalelement->StrainRateMLHO(&epsilon[0],xyz_list,gauss,
     1895                        basalelement->StrainRateMOLHO(&epsilon[0],xyz_list,gauss,
    18901896                  vxbase_input,vybase_input,vxshear_input,vyshear_input,thickness_input,n_input,zeta);
    18911897
    1892                         basalelement->dViscositydBMLHO(&dmudB,dim,xyz_list,gauss,vxbase_input,vybase_input,vxshear_input,vyshear_input,thickness_input,n_input,zeta);
     1898                        basalelement->dViscositydBMOLHO(&dmudB,dim,xyz_list,gauss,vxbase_input,vybase_input,vxshear_input,vyshear_input,thickness_input,n_input,zeta);
    18931899
    18941900                        e1[0] = 2.0*epsilon[0]+epsilon[1];
     
    22452251        delete gauss;
    22462252}/*}}}*/
    2247 void           AdjointHorizAnalysis::GradientJBMLHO(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index){/*{{{*/
     2253void           AdjointHorizAnalysis::GradientJBMOLHO(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index){/*{{{*/
    22482254        _error_("not implemented yet...");
    22492255}/*}}}*/
     
    26452651        delete friction;
    26462652}/*}}}*/
    2647 void           AdjointHorizAnalysis::GradientJDragMLHO(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index){/*{{{*/
     2653void           AdjointHorizAnalysis::GradientJDragMOLHO(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index){/*{{{*/
    26482654
    26492655        /*return if floating (gradient is 0)*/
     
    32663272                InputUpdateFromSolutionFS(solution,element);
    32673273        }
    3268         else if (approximation==MLHOApproximationEnum) {
    3269                 InputUpdateFromSolutionMLHO(solution, element);
     3274        else if (approximation==MOLHOApproximationEnum) {
     3275                InputUpdateFromSolutionMOLHO(solution, element);
    32703276        }
    32713277        else{
     
    34143420        xDelete<int>(doflist);
    34153421}/*}}}*/
    3416 void           AdjointHorizAnalysis::InputUpdateFromSolutionMLHO(IssmDouble* solution,Element* element){/*{{{*/
     3422void           AdjointHorizAnalysis::InputUpdateFromSolutionMOLHO(IssmDouble* solution,Element* element){/*{{{*/
    34173423        int  i;
    34183424        int* doflist=NULL;
     
    34273433
    34283434        /*Fetch dof list and allocate solution vectors*/
    3429         element->GetDofListLocal(&doflist,MLHOApproximationEnum,GsetEnum);
    3430         IssmDouble* values  = xNew<IssmDouble>(numdof);
    3431         IssmDouble* lambdax = xNew<IssmDouble>(numnodes);
    3432         IssmDouble* lambday = xNew<IssmDouble>(numnodes);
    3433         IssmDouble* lambdabx = xNew<IssmDouble>(numnodes);
    3434         IssmDouble* lambdaby = xNew<IssmDouble>(numnodes);
     3435        element->GetDofListLocal(&doflist,MOLHOApproximationEnum,GsetEnum);
     3436        IssmDouble* values    = xNew<IssmDouble>(numdof);
     3437        IssmDouble* lambdax   = xNew<IssmDouble>(numnodes);
     3438        IssmDouble* lambday   = xNew<IssmDouble>(numnodes);
     3439        IssmDouble* lambdabx  = xNew<IssmDouble>(numnodes);
     3440        IssmDouble* lambdaby  = xNew<IssmDouble>(numnodes);
    34353441        IssmDouble* lambdashx = xNew<IssmDouble>(numnodes);
    34363442        IssmDouble* lambdashy = xNew<IssmDouble>(numnodes);
    3437         IssmDouble* n                    = xNew<IssmDouble>(numnodes);
     3443        IssmDouble* n        = xNew<IssmDouble>(numnodes);
    34383444
    34393445        /*Use the dof list to index into the solution vector: */
     
    34853491        xDelete<IssmDouble>(lambdashx);
    34863492        xDelete<IssmDouble>(lambdashy);
     3493   xDelete<IssmDouble>(n);
    34873494        xDelete<int>(doflist);
    34883495}/*}}}*/
  • issm/trunk/src/c/analyses/AdjointHorizAnalysis.h

    r26744 r27035  
    2828                ElementMatrix* CreateKMatrixFS(Element* element);
    2929                ElementMatrix* CreateKMatrixHO(Element* element);
    30                 ElementMatrix* CreateKMatrixMLHO(Element* element);
    31                 ElementMatrix* CreateKMatrixMLHOVerticalIntergrated(Element* element);
     30                ElementMatrix* CreateKMatrixMOLHO(Element* element);
     31                ElementMatrix* CreateKMatrixMOLHOVerticalIntergrated(Element* element);
    3232                ElementMatrix* CreateKMatrixL1L2(Element* element);
    3333                ElementMatrix* CreateKMatrixSSA(Element* element);
     
    3636                ElementVector* CreatePVectorL1L2(Element* element);
    3737                ElementVector* CreatePVectorHO(Element* element);
    38                 ElementVector* CreatePVectorMLHO(Element* element);
     38                ElementVector* CreatePVectorMOLHO(Element* element);
    3939                ElementVector* CreatePVectorSSA(Element* element);
    4040                void           GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element);
     
    4545                void           GradientJBbarL1L2(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
    4646                void           GradientJBbarHO(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
    47                 void           GradientJBbarMLHO(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
     47                void           GradientJBbarMOLHO(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
    4848                void           GradientJBbarSSA(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
    4949                void           GradientJBFS(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
    5050                void           GradientJBGradient(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
    5151                void           GradientJBHO(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
    52                 void           GradientJBMLHO(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
     52                void           GradientJBMOLHO(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
    5353                void           GradientJBSSA(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
    5454                void           GradientJDragFS(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
     
    5656                void           GradientJDragL1L2(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
    5757                void           GradientJDragHO(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
    58                 void           GradientJDragMLHO(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
     58                void           GradientJDragMOLHO(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
    5959                void           GradientJDragSSA(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
    6060                void           GradientJDragHydroFS(Element* element,Vector<IssmDouble>* gradient,int control_interp,int control_index);
     
    6666                void           InputUpdateFromSolutionFS(IssmDouble* solution,Element* element);
    6767                void           InputUpdateFromSolutionHoriz(IssmDouble* solution,Element* element);
    68                 void           InputUpdateFromSolutionMLHO(IssmDouble* solution,Element* element);
     68                void           InputUpdateFromSolutionMOLHO(IssmDouble* solution,Element* element);
    6969                void           UpdateConstraints(FemModel* femmodel);
    7070};
  • issm/trunk/src/c/analyses/BalancethicknessAnalysis.cpp

    r26744 r27035  
    552552}/*}}}*/
    553553void           BalancethicknessAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
    554         /*Default, do nothing*/
    555         return;
    556 }/*}}}*/
     554        SetActiveNodesLSMx(femmodel);
     555}/*}}}*/
  • issm/trunk/src/c/analyses/FreeSurfaceBaseAnalysis.cpp

    r26744 r27035  
    7373        }
    7474
    75         iomodel->FetchDataToInput(inputs,elements,"md.geometry.surface",SurfaceEnum);
     75        iomodel->FetchDataToInput(inputs,elements,"md.geometry.base",BaseEnum);
    7676        iomodel->FetchDataToInput(inputs,elements,"md.initialization.sealevel",SealevelEnum,0);
    7777        iomodel->FetchDataToInput(inputs,elements,"md.mask.ice_levelset",MaskIceLevelsetEnum);
     
    9696                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.floatingice_melting_rate",BasalforcingsFloatingiceMeltingRateEnum);
    9797                        if(isstochastic){
    98             iomodel->FetchDataToInput(inputs,elements,"md.stochasticforcing.default_id",StochasticForcingDefaultIdEnum);
    99             iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.floatingice_melting_rate",BaselineBasalforcingsFloatingiceMeltingRateEnum);
    100          }
     98                                iomodel->FetchDataToInput(inputs,elements,"md.stochasticforcing.default_id",StochasticForcingDefaultIdEnum);
     99                                iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.floatingice_melting_rate",BaselineBasalforcingsFloatingiceMeltingRateEnum);
     100                        }
    101101                        break;
    102102                case LinearFloatingMeltRateEnum:
     
    108108                        break;
    109109                case SpatialLinearFloatingMeltRateEnum:
    110                         iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_melting_rate",BasalforcingsDeepwaterMeltingRateEnum);
    111                         iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_elevation",BasalforcingsDeepwaterElevationEnum);
    112                         iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.upperwater_elevation",BasalforcingsUpperwaterElevationEnum);
     110                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_melting_rate",BasalforcingsSpatialDeepwaterMeltingRateEnum);
     111                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_elevation",BasalforcingsSpatialDeepwaterElevationEnum);
     112                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.upperwater_melting_rate",BasalforcingsSpatialUpperwaterMeltingRateEnum);
     113                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.upperwater_elevation",BasalforcingsSpatialUpperwaterElevationEnum);
     114                        if(isstochastic){
     115                                iomodel->FetchDataToInput(inputs,elements,"md.stochasticforcing.default_id",StochasticForcingDefaultIdEnum);
     116                                iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_melting_rate",BaselineBasalforcingsSpatialDeepwaterMeltingRateEnum);
     117                        }
    113118                        break;
    114119                case BasalforcingsPicoEnum:
     
    143148}/*}}}*/
    144149ElementMatrix* FreeSurfaceBaseAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
    145 _error_("Not implemented");
     150        _error_("Not implemented");
    146151}/*}}}*/
    147152ElementMatrix* FreeSurfaceBaseAnalysis::CreateKMatrix(Element* element){/*{{{*/
     
    152157        IssmDouble *xyz_list  = NULL;
    153158        IssmDouble  Jdet,D_scalar,dt,h;
    154         IssmDouble  vel,vx,vy;
     159        IssmDouble  vel,vx,vy,tau;
    155160
    156161        /*Get basal element*/
     
    225230                }
    226231
    227                 if(stabilization==2){
    228                         /*Streamline upwinding*/
    229                         if(dim==1){
    230                          vel=fabs(vx)+1.e-8;
    231                          D[0] = h/(2.*vel)*vx*vx;
    232                         }
    233                         else{
    234                          vel=sqrt(vx*vx+vy*vy)+1.e-8;
    235                          D[0*dim+0]=h/(2*vel)*vx*vx;
    236                          D[1*dim+0]=h/(2*vel)*vy*vx;
    237                          D[0*dim+1]=h/(2*vel)*vx*vy;
    238                          D[1*dim+1]=h/(2*vel)*vy*vy;
    239                         }
    240                 }
    241                 else if(stabilization==1){
     232                if(stabilization==1){
    242233                        /*SSA*/
    243234                        if(dim==1){
     
    250241                                D[0*dim+0]=h/2.0*fabs(vx);
    251242                                D[1*dim+1]=h/2.0*fabs(vy);
     243                        }
     244                }
     245                else if(stabilization==2){
     246                        /*Streamline upwinding*/
     247                        if(dim==1){
     248                                vel=fabs(vx)+1.e-8;
     249                                D[0] = h/(2.*vel)*vx*vx;
     250                        }
     251                        else{
     252                                vel=sqrt(vx*vx+vy*vy)+1.e-8;
     253                                D[0*dim+0]=h/(2*vel)*vx*vx;
     254                                D[1*dim+0]=h/(2*vel)*vy*vx;
     255                                D[0*dim+1]=h/(2*vel)*vx*vy;
     256                                D[1*dim+1]=h/(2*vel)*vy*vy;
     257                        }
     258
     259                }
     260                else if(stabilization==5){
     261                        /*SUPG*/
     262                        if(dim==1){
     263                                vx_input->GetInputAverage(&vx);
     264                                tau=h/(2.*fabs(vx)+1e-10);
     265                        }
     266                        else{
     267                                vx_input->GetInputAverage(&vx);
     268                                vy_input->GetInputAverage(&vy);
     269                                tau=1*h/(2.*pow(vx*vx+vy*vy,0.5)+1e-10);
    252270                        }
    253271                }
     
    258276                                        for(int j=0;j<numnodes;j++){
    259277                                                Ke->values[i*numnodes+j] += (
    260                                                                         dbasis[0*numnodes+i] *(D[0*dim+0]*dbasis[0*numnodes+j] + D[0*dim+1]*dbasis[1*numnodes+j]) +
    261                                                                         dbasis[1*numnodes+i] *(D[1*dim+0]*dbasis[0*numnodes+j] + D[1*dim+1]*dbasis[1*numnodes+j])
    262                                                                         );
     278                                                                dbasis[0*numnodes+i] *(D[0*dim+0]*dbasis[0*numnodes+j] + D[0*dim+1]*dbasis[1*numnodes+j]) +
     279                                                                dbasis[1*numnodes+i] *(D[1*dim+0]*dbasis[0*numnodes+j] + D[1*dim+1]*dbasis[1*numnodes+j])
     280                                                                );
    263281                                        }
    264282                                }
     
    266284                        else{
    267285                                for(int i=0;i<numnodes;i++) for(int j=0;j<numnodes;j++) Ke->values[i*numnodes+j] += dbasis[0*numnodes+i]*D[0]*dbasis[0*numnodes+j];
     286                        }
     287                }
     288                else if(stabilization==5){
     289                        D_scalar=gauss->weight*Jdet*dt;
     290                        if(dim==2){
     291                                for(int i=0;i<numnodes;i++){
     292                                        for(int j=0;j<numnodes;j++){
     293                                                Ke->values[i*numnodes+j]+=tau*D_scalar*
     294                                                        (vx*dbasis[0*numnodes+i]+vy*dbasis[1*numnodes+i])*
     295                                                        (vx*dbasis[0*numnodes+j]+vy*dbasis[1*numnodes+j]);
     296                                        }
     297                                }
     298                        }
     299                        else{
     300                                for(int i=0;i<numnodes;i++) for(int j=0;j<numnodes;j++) Ke->values[i*numnodes+j]+=tau*D_scalar*(vx*dbasis[0*numnodes+i])*(vx*dbasis[0*numnodes+j]);
    268301                        }
    269302                }
     
    280313}/*}}}*/
    281314ElementVector* FreeSurfaceBaseAnalysis::CreatePVector(Element* element){/*{{{*/
     315
    282316        /*Intermediaries*/
    283         int         domaintype,dim;
     317        int         domaintype,dim,stabilization;
    284318        IssmDouble  Jdet,dt;
    285         IssmDouble  gmb,fmb,mb,bed,phi,vz;
     319        IssmDouble  gmb,fmb,mb,bed,vx,vy,vz,tau;
    286320        Element*    basalelement = NULL;
    287321        IssmDouble *xyz_list  = NULL;
     
    309343        /*Fetch number of nodes and dof for this finite element*/
    310344        int numnodes = basalelement->GetNumberOfNodes();
     345        int         melt_style,point1;
     346        IssmDouble  fraction1,fraction2;
     347        bool        mainlyfloating;
    311348
    312349        /*Initialize Element vector and other vectors*/
    313350        ElementVector* pe    = basalelement->NewElementVector();
    314351        IssmDouble*    basis = xNew<IssmDouble>(numnodes);
     352        IssmDouble*    dbasis = xNew<IssmDouble>(dim*numnodes);
     353        IssmDouble  gllevelset,phi=1.;
    315354
    316355        /*Retrieve all inputs and parameters*/
    317         basalelement->GetVerticesCoordinates(&xyz_list);
    318356        basalelement->FindParam(&dt,TimesteppingTimeStepEnum);
     357        basalelement->FindParam(&melt_style,GroundinglineMeltInterpolationEnum);
    319358        Input* groundedice_input   = basalelement->GetInput(MaskOceanLevelsetEnum);              _assert_(groundedice_input);
    320359        Input* gmb_input           = basalelement->GetInput(BasalforcingsGroundediceMeltingRateEnum);  _assert_(gmb_input);
    321360        Input* fmb_input           = basalelement->GetInput(BasalforcingsFloatingiceMeltingRateEnum);  _assert_(fmb_input);
    322361        Input* base_input          = basalelement->GetInput(BaseEnum);                                 _assert_(base_input);
    323         Input* vz_input      = NULL;
     362        Input* gllevelset_input = basalelement->GetInput(MaskOceanLevelsetEnum);              _assert_(gllevelset_input);
     363        Input* vz_input = NULL;
     364        Input* vx_input = NULL;
     365        Input* vy_input = NULL;
    324366        switch(dim){
    325                 case 1: vz_input = basalelement->GetInput(VyEnum); _assert_(vz_input); break;
    326                 case 2: vz_input = basalelement->GetInput(VzEnum); _assert_(vz_input); break;
     367                case 1:
     368                        vx_input=basalelement->GetInput(VxEnum); _assert_(vx_input);
     369                        vz_input=basalelement->GetInput(VyEnum) ; _assert_(vz_input);
     370                        break;
     371                case 2:
     372                        vx_input=basalelement->GetInput(VxEnum); _assert_(vx_input);
     373                        vy_input=basalelement->GetInput(VyEnum); _assert_(vy_input);
     374                        vz_input=basalelement->GetInput(VzEnum); _assert_(vz_input);
     375                        break;
    327376                default: _error_("not implemented");
    328377        }
     378        IssmDouble h = basalelement->CharacteristicLength();
     379
     380        /*Recover portion of element that is grounded*/
     381        basalelement->GetVerticesCoordinates(&xyz_list);
     382        phi=basalelement->GetGroundedPortion(xyz_list);
     383        Gauss*      gauss     = NULL;
     384        if(melt_style==SubelementMelt2Enum){
     385                basalelement->GetGroundedPart(&point1,&fraction1,&fraction2,&mainlyfloating);
     386                gauss = basalelement->NewGauss(point1,fraction1,fraction2,3);
     387        }
     388        else{
     389                gauss = basalelement->NewGauss(3);   
     390        }
    329391
    330392        /* Start  looping on the number of gaussian points: */
    331         Gauss* gauss=basalelement->NewGauss(2);
    332393        while(gauss->next()){
    333394
     
    335396                basalelement->NodalFunctions(basis,gauss);
    336397
    337                 vz_input->GetInputValue(&vz,gauss);
     398
     399                vz_input->GetInputValue(&vz,gauss); 
    338400                gmb_input->GetInputValue(&gmb,gauss);
    339401                fmb_input->GetInputValue(&fmb,gauss);
    340402                base_input->GetInputValue(&bed,gauss);
    341403                groundedice_input->GetInputValue(&phi,gauss);
    342                 if(phi>0) mb=gmb;
    343                 else mb=fmb;
     404                gllevelset_input->GetInputValue(&gllevelset,gauss);
     405                if(melt_style==SubelementMelt1Enum){
     406                        //if (phi>0.999999999) mb=gmb;
     407                        //else mb=(1-phi)*fmb+phi*gmb; // phi is the fraction of grounded ice so (1-phi) is floating
     408                        if(phi>0) mb=gmb;
     409                        else mb=fmb;
     410                }
     411                else if(melt_style==SubelementMelt2Enum){
     412                        if(gllevelset>0.) mb=gmb;
     413                        else mb=fmb;
     414                }
     415                else if(melt_style==NoMeltOnPartiallyFloatingEnum){
     416                        if (phi<0.00000001) mb=fmb; 
     417                        else mb=gmb;
     418                }
     419                else if(melt_style==FullMeltOnPartiallyFloatingEnum){
     420                        if (phi<0.99999999) mb=fmb; 
     421                        else mb=gmb;
     422                }
     423                else  _error_("melt interpolation "<<EnumToStringx(melt_style)<<" not implemented yet");
    344424
    345425                for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(bed+dt*(mb) + dt*vz)*basis[i];
     426
     427                if(stabilization==5){
     428                        /*SUPG*/
     429                        basalelement->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
     430                        if(dim==1){
     431                                vx_input->GetInputAverage(&vx);
     432                                tau=h/(2.*fabs(vx)+1e-10);
     433                                for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(dt*mb+dt*vz)*tau*(vx*dbasis[0*numnodes+i]);
     434                        }
     435                        else{
     436                                vx_input->GetInputAverage(&vx);
     437                                vy_input->GetInputAverage(&vy);
     438                                tau=1*h/(2.*pow(vx*vx+vy*vy,0.5)+1e-10);
     439                                for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(bed*0.+dt*mb+dt*vz)*tau*(vx*dbasis[0*numnodes+i]+vy*dbasis[1*numnodes+i]);
     440                        }
     441                }
    346442        }
    347443
     
    349445        xDelete<IssmDouble>(xyz_list);
    350446        xDelete<IssmDouble>(basis);
     447        xDelete<IssmDouble>(dbasis);
    351448        delete gauss;
    352449        if(basalelement->IsSpawnedElement()){basalelement->DeleteMaterials(); delete basalelement;};
     
    355452}/*}}}*/
    356453void           FreeSurfaceBaseAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
    357            _error_("not implemented yet");
     454        _error_("not implemented yet");
    358455}/*}}}*/
    359456void           FreeSurfaceBaseAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element*  element,int control_type,int control_interp,int control_index){/*{{{*/
  • issm/trunk/src/c/analyses/FreeSurfaceTopAnalysis.cpp

    r26744 r27035  
    8080        iomodel->FetchDataToInput(inputs,elements,"md.mask.ice_levelset",MaskIceLevelsetEnum);
    8181        iomodel->FetchDataToInput(inputs,elements,"md.initialization.vx",VxEnum);
     82        iomodel->FetchDataToInput(inputs,elements,"md.initialization.vy",VyEnum);
    8283        if(iomodel->domaintype!=Domain2DhorizontalEnum){
    8384                iomodel->FetchDataToInput(inputs,elements,"md.mesh.vertexonsurface",MeshVertexonsurfaceEnum);
     
    111112}/*}}}*/
    112113ElementMatrix* FreeSurfaceTopAnalysis::CreateJacobianMatrix(Element* element){/*{{{*/
    113 _error_("Not implemented");
     114        _error_("Not implemented");
    114115}/*}}}*/
    115116ElementMatrix* FreeSurfaceTopAnalysis::CreateKMatrix(Element* element){/*{{{*/
     
    120121        IssmDouble *xyz_list  = NULL;
    121122        IssmDouble  Jdet,D_scalar,dt,h;
    122         IssmDouble  vel,vx,vy;
     123        IssmDouble  vel,vx,vy,tau;
    123124
    124125        /*Get top element*/
     
    195196                }
    196197
    197                 if(stabilization==2){
     198                if(stabilization==1){
     199                        /*artifical diffusion*/
     200                        if(dim==1){
     201                                vx_input->GetInputAverage(&vx);
     202                                D[0]=h/2.*fabs(vx);
     203                        }
     204                        else{
     205                                vx_input->GetInputAverage(&vx);
     206                                vy_input->GetInputAverage(&vy);
     207
     208                                D[0*dim+0]=h/2.0*fabs(vx);
     209                                D[1*dim+1]=h/2.0*fabs(vy);
     210                        }
     211                }
     212                else if(stabilization==2){
    198213                        /*Streamline upwinding*/
    199214                        if(dim==1){
     
    209224                        }
    210225                }
    211                 else if(stabilization==1){
    212                         /*SSA*/
     226                else if(stabilization==5){
     227                        /*SUPG*/
    213228                        if(dim==1){
    214229                                vx_input->GetInputAverage(&vx);
    215                                 D[0]=h/2.*fabs(vx);
     230                                tau=h/(2.*fabs(vx)+1e-10);
    216231                        }
    217232                        else{
    218233                                vx_input->GetInputAverage(&vx);
    219234                                vy_input->GetInputAverage(&vy);
    220 
    221                                 D[0*dim+0]=h/2.0*fabs(vx);
    222                                 D[1*dim+1]=h/2.0*fabs(vy);
     235                                tau=1*h/(2.*pow(vx*vx+vy*vy,0.5)+1e-10);
    223236                        }
    224237                }
     
    229242                                        for(int j=0;j<numnodes;j++){
    230243                                                Ke->values[i*numnodes+j] += (
    231                                                                         dbasis[0*numnodes+i] *(D[0*dim+0]*dbasis[0*numnodes+j] + D[0*dim+1]*dbasis[1*numnodes+j]) +
    232                                                                         dbasis[1*numnodes+i] *(D[1*dim+0]*dbasis[0*numnodes+j] + D[1*dim+1]*dbasis[1*numnodes+j])
    233                                                                         );
     244                                                                dbasis[0*numnodes+i] *(D[0*dim+0]*dbasis[0*numnodes+j] + D[0*dim+1]*dbasis[1*numnodes+j]) +
     245                                                                dbasis[1*numnodes+i] *(D[1*dim+0]*dbasis[0*numnodes+j] + D[1*dim+1]*dbasis[1*numnodes+j])
     246                                                                );
    234247                                        }
    235248                                }
     
    237250                        else{
    238251                                for(int i=0;i<numnodes;i++) for(int j=0;j<numnodes;j++) Ke->values[i*numnodes+j] += dbasis[0*numnodes+i]*D[0]*dbasis[0*numnodes+j];
     252                        }
     253                }
     254                else if(stabilization==5){
     255                        D_scalar=gauss->weight*Jdet*dt;
     256                        if(dim==2){
     257                                for(int i=0;i<numnodes;i++){
     258                                        for(int j=0;j<numnodes;j++){
     259                                                Ke->values[i*numnodes+j]+=tau*D_scalar*
     260                                                        (vx*dbasis[0*numnodes+i]+vy*dbasis[1*numnodes+i])*
     261                                                        (vx*dbasis[0*numnodes+j]+vy*dbasis[1*numnodes+j]);
     262                                        }
     263                                }
     264                        }
     265                        else{
     266                                for(int i=0;i<numnodes;i++) for(int j=0;j<numnodes;j++) Ke->values[i*numnodes+j]+=tau*D_scalar*(vx*dbasis[0*numnodes+i])*(vx*dbasis[0*numnodes+j]);
    239267                        }
    240268                }
     
    251279}/*}}}*/
    252280ElementVector* FreeSurfaceTopAnalysis::CreatePVector(Element* element){/*{{{*/
     281
    253282        /*Intermediaries*/
    254         int         domaintype,dim;
     283        int         domaintype,dim,stabilization;
    255284        IssmDouble  Jdet,dt;
    256         IssmDouble  ms,surface,vz;
     285        IssmDouble  ms,surface,vx,vy,vz,tau;
    257286        Element*    topelement = NULL;
    258287        IssmDouble *xyz_list  = NULL;
     
    284313        ElementVector* pe    = topelement->NewElementVector();
    285314        IssmDouble*    basis = xNew<IssmDouble>(numnodes);
     315        IssmDouble*    dbasis = xNew<IssmDouble>(dim*numnodes);
    286316
    287317        /*Retrieve all inputs and parameters*/
    288318        topelement->GetVerticesCoordinates(&xyz_list);
    289319        topelement->FindParam(&dt,TimesteppingTimeStepEnum);
    290         Input* ms_input      = topelement->GetInput(SmbMassBalanceEnum);  _assert_(ms_input);
    291         Input* surface_input = topelement->GetInput(SurfaceEnum);                     _assert_(surface_input);
    292         Input* vz_input      = NULL;
     320        Input *ms_input      = topelement->GetInput(SmbMassBalanceEnum); _assert_(ms_input);
     321        Input *surface_input = topelement->GetInput(SurfaceEnum);        _assert_(surface_input);
     322        Input *vz_input      = NULL;
     323        Input *vx_input      = NULL;
     324        Input *vy_input      = NULL;
    293325        switch(dim){
    294                 case 1: vz_input = topelement->GetInput(VyEnum); _assert_(vz_input); break;
    295                 case 2: vz_input = topelement->GetInput(VzEnum); _assert_(vz_input); break;
     326                case 1:
     327                        vx_input=topelement->GetInput(VxEnum); _assert_(vx_input);
     328                        vz_input = topelement->GetInput(VyEnum) ; _assert_(vz_input);
     329                        break;
     330                case 2:
     331                        vx_input=topelement->GetInput(VxEnum); _assert_(vx_input);
     332                        vy_input = topelement->GetInput(VyEnum); _assert_(vy_input);
     333                        vz_input = topelement->GetInput(VzEnum); _assert_(vz_input);
     334                        break;
    296335                default: _error_("not implemented");
    297336        }
     337        IssmDouble h = topelement->CharacteristicLength();
    298338
    299339        /*Initialize mb_correction to 0, do not forget!:*/
     
    312352        }
    313353
     354        if(stabilization==5){
     355                /*SUPG*/
     356                topelement->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
     357                if(dim==1){
     358                        vx_input->GetInputAverage(&vx);
     359                        tau=h/(2.*fabs(vx)+1e-10);
     360                        for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(dt*ms+dt*vz)*tau*(vx*dbasis[0*numnodes+i]);
     361                }
     362                else{
     363                        vx_input->GetInputAverage(&vx);
     364                        vy_input->GetInputAverage(&vy);
     365                        tau=h/(2.*pow(vx*vx+vy*vy,0.5)+1e-10);
     366                        for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*(dt*ms+dt*vz)*tau*(vx*dbasis[0*numnodes+i]+vy*dbasis[1*numnodes+i]);
     367                }
     368        }
     369
    314370        /*Clean up and return*/
    315371        xDelete<IssmDouble>(xyz_list);
    316372        xDelete<IssmDouble>(basis);
     373        xDelete<IssmDouble>(dbasis);
    317374        delete gauss;
    318375        if(topelement->IsSpawnedElement()){topelement->DeleteMaterials(); delete topelement;};
     
    321378}/*}}}*/
    322379void           FreeSurfaceTopAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/
    323            _error_("not implemented yet");
     380        _error_("not implemented yet");
    324381}/*}}}*/
    325382void           FreeSurfaceTopAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element*  element,int control_type,int control_interp,int control_index){/*{{{*/
     
    329386
    330387        element->InputUpdateFromSolutionOneDof(solution,SurfaceEnum);
     388
     389        /*Now, we need to do some "processing"*/
     390        int numvertices = element->GetNumberOfVertices();
     391        int        migration_style;
     392
     393        IssmDouble* surface = xNew<IssmDouble>(numvertices);
     394        IssmDouble* newsurface = xNew<IssmDouble>(numvertices);
     395        IssmDouble* thickness = xNew<IssmDouble>(numvertices);
     396        IssmDouble* base = xNew<IssmDouble>(numvertices);
     397        IssmDouble* bed = xNew<IssmDouble>(numvertices);
     398        IssmDouble* phi = xNew<IssmDouble>(numvertices);
     399        IssmDouble* sealevel = xNew<IssmDouble>(numvertices);
     400
     401        IssmDouble minthickness = element->FindParam(MasstransportMinThicknessEnum);
     402        IssmDouble rho_ice      = element->FindParam(MaterialsRhoIceEnum);
     403        IssmDouble rho_water    = element->FindParam(MaterialsRhoSeawaterEnum);
     404
     405        bool isgroundingline;
     406        element->FindParam(&isgroundingline,TransientIsgroundinglineEnum);
     407        element->FindParam(&migration_style,GroundinglineMigrationEnum);
     408        if(isgroundingline) element->GetInputListOnVertices(&bed[0],BedEnum);
     409
     410        element->GetInputListOnVertices(&base[0],BaseEnum);
     411        element->GetInputListOnVertices(&surface[0],SurfaceEnum);
     412        element->GetInputListOnVertices(&phi[0],MaskOceanLevelsetEnum);
     413        element->GetInputListOnVertices(&sealevel[0],SealevelEnum);
     414
     415        for(int i=0;i<numvertices;i++){
     416                newsurface[i]=surface[i];
     417                thickness[i]=surface[i]-base[i];
     418                /*Check solution*/
     419                if(xIsNan<IssmDouble>(thickness[i])) _error_("NaN found in solution vector");
     420                if(xIsInf<IssmDouble>(thickness[i])) _error_("Inf found in solution vector");
     421
     422                /* check for thickness<minthickness */
     423                if(thickness[i]<minthickness){
     424                        thickness[i]=minthickness;
     425                        if(phi[i]>0.){
     426                                if(base[i]<=bed[i]) base[i] = bed[i];
     427                                newsurface[i] = base[i]+minthickness;
     428                        }else{
     429                                // assume floatation condition
     430                                newsurface[i] = (1.-rho_ice/rho_water)*minthickness;
     431                                base[i] = -rho_ice/rho_water*minthickness;
     432                        }
     433                }
     434
     435                /* update thickness */
     436                thickness[i]=newsurface[i]-base[i];
     437                /* some checks */
     438                if(thickness[i]<0.) _error_("thickness<0");
     439                if(newsurface[i]<base[i]) _error_("surface<base");
     440        }
     441
     442        /* update inputs */
     443        element->AddInput(BaseEnum,base,element->GetElementType());
     444        element->AddInput(SurfaceEnum,newsurface,element->GetElementType());
     445        element->AddInput(ThicknessEnum,thickness,element->GetElementType());
     446
     447        /* Free resources */
     448        xDelete<IssmDouble>(newsurface);
     449        xDelete<IssmDouble>(surface);
     450        xDelete<IssmDouble>(thickness);
     451        xDelete<IssmDouble>(base);
     452        xDelete<IssmDouble>(bed);
     453        xDelete<IssmDouble>(phi);
     454        xDelete<IssmDouble>(sealevel);
    331455}/*}}}*/
    332456void           FreeSurfaceTopAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
  • issm/trunk/src/c/analyses/HydrologyGlaDSAnalysis.cpp

    r26744 r27035  
    472472
    473473        /*Skip if water or ice shelf element*/
    474         if(element->IsAllFloating()) return;
     474        //if(element->IsAllFloating()) return;
    475475
    476476        /*Intermediaries */
     
    543543                if(h_new[iv]<AEPS) h_new[iv] = AEPS;
    544544        }
     545       
     546        /*Force floating ice to have zero sheet thickness*/
     547        if(element->IsAllFloating()){
     548                for(int iv=0;iv<numvertices;iv++) h_new[iv] = 0.;
     549        }
    545550
    546551        element->AddInput(HydrologySheetThicknessEnum,h_new,P1Enum);
     
    561566
    562567        /*Skip if water or ice shelf element*/
    563         if(element->IsAllFloating()) return;
     568        //if(element->IsAllFloating()) return;
    564569
    565570        /*Intermediary*/
     
    604609        }
    605610
     611   /*Force floating ice to have zero effective pressure*/
     612   if(element->IsAllFloating()){
     613                for(int iv=0;iv<numnodes;iv++) N[iv] = 0.;
     614        }
     615
    606616        element->AddInput(EffectivePressureEnum,N,element->FiniteElement());
    607 
     617       
    608618        /*Clean up and return*/
    609619        delete gauss;
  • issm/trunk/src/c/analyses/HydrologyShaktiAnalysis.cpp

    r26744 r27035  
    286286        IssmDouble  lr,br,vx,vy,beta,lc;
    287287        IssmDouble  alpha2,frictionheat;
    288    IssmDouble  PMPheat,dpressure_water[2],dbed[2];     
     288   IssmDouble  PMPheat,dissipation,dpressure_water[2],dbed[2]; 
    289289        IssmDouble* xyz_list = NULL;
    290290//        IssmDouble dgapxx; /***/
     
    381381        dpressure_water[0] = rho_water*g*(dh[0] - dbed[0]);
    382382                dpressure_water[1] = rho_water*g*(dh[1] - dbed[1]);
    383                 PMPheat=-CT*CW*conductivity*(dh[0]*dpressure_water[0]+dh[1]*dpressure_water[1]);
     383                PMPheat=CT*CW*conductivity*rho_water*(dh[0]*dpressure_water[0]+dh[1]*dpressure_water[1]);
     384                PMPheat=0; /*** TEST no PMPheat***/
    384385
    385386        meltrate = 1/latentheat*(G+frictionheat+rho_water*g*conductivity*(dh[0]*dh[0]+dh[1]*dh[1])-PMPheat);
    386                 _assert_(meltrate>0.);
    387387
    388388                  for(int i=0;i<numnodes;i++) pe->values[i]+=Jdet*gauss->weight*
     
    549549        IssmDouble  alpha2,frictionheat;
    550550        IssmDouble* xyz_list = NULL;
    551    IssmDouble  dpressure_water[2],dbed[2],PMPheat;
     551   IssmDouble  dpressure_water[2],dbed[2],PMPheat,dissipation;
    552552        IssmDouble q = 0.;
    553553   IssmDouble channelization = 0.;
     
    629629           dpressure_water[0] = rho_water*g*(dh[0] - dbed[0]);
    630630                dpressure_water[1] = rho_water*g*(dh[1] - dbed[1]);
    631                 PMPheat=-CT*CW*conductivity*(dh[0]*dpressure_water[0]+dh[1]*dpressure_water[1]);
     631                PMPheat=CT*CW*conductivity*rho_water*(dh[0]*dpressure_water[0]+dh[1]*dpressure_water[1]);
     632PMPheat=0; /*** TEST no PMPheat***/
     633                dissipation=rho_water*g*conductivity*(dh[0]*dh[0]+dh[1]*dh[1]);
    632634
    633635                meltrate = 1/latentheat*(G+frictionheat+rho_water*g*conductivity*(dh[0]*dh[0]+dh[1]*dh[1])-PMPheat);
    634                 _assert_(meltrate>0.);
     636
     637                element->AddInput(DummyEnum,&meltrate,P0Enum);
     638                element->AddInput(EsaEmotionEnum,&frictionheat,P0Enum);
     639                element->AddInput(EsaNmotionEnum,&dissipation,P0Enum);
     640                element->AddInput(EsaUmotionEnum,&PMPheat,P0Enum);
     641
    635642
    636643                newgap += gauss->weight*Jdet*(gap+dt*(
     
    664671
    665672        /*Limit gap height to grow to surface*/
    666         if(newgap>thickness)
    667          newgap = thickness;
     673//      if(newgap>thickness)
     674//       newgap = thickness;
     675        if(newgap>1)
     676         newgap = 1;
    668677
    669678        /*Add new gap as an input*/
  • issm/trunk/src/c/analyses/HydrologyTwsAnalysis.cpp

    r26744 r27035  
    4444}/*}}}*/
    4545void HydrologyTwsAnalysis::UpdateParameters(Parameters* parameters,IoModel* iomodel,int solution_enum,int analysis_enum){/*{{{*/
     46
     47        /*retrieve some parameters: */
     48        int    hydrology_model;
     49        int    numoutputs;
     50        char** requestedoutputs = NULL;
     51        iomodel->FindConstant(&hydrology_model,"md.hydrology.model");
     52
     53        /*Now, do we really want Tws?*/
     54        if(hydrology_model!=HydrologyTwsEnum) return;
     55
     56        parameters->AddObject(new IntParam(HydrologyModelEnum,hydrology_model));
     57
     58        /*Requested outputs*/
     59        iomodel->FindConstant(&requestedoutputs,&numoutputs,"md.hydrology.requested_outputs");
     60        parameters->AddObject(new IntParam(HydrologyNumRequestedOutputsEnum,numoutputs));
     61        if(numoutputs)parameters->AddObject(new StringArrayParam(HydrologyRequestedOutputsEnum,requestedoutputs,numoutputs));
     62        iomodel->DeleteData(&requestedoutputs,numoutputs,"md.hydrology.requested_outputs");
    4663
    4764}/*}}}*/
  • issm/trunk/src/c/analyses/LevelsetAnalysis.cpp

    r26744 r27035  
    1010#include "../modules/modules.h"
    1111#include "../solutionsequences/solutionsequences.h"
     12#include <math.h>
    1213
    1314void LevelsetAnalysis::CreateConstraints(Constraints* constraints,IoModel* iomodel){/*{{{*/
     
    7980
    8081        iomodel->FetchDataToInput(inputs,elements,"md.mask.ice_levelset",MaskIceLevelsetEnum);
     82        iomodel->FetchDataToInput(inputs,elements,"md.mask.ocean_levelset",MaskOceanLevelsetEnum);
    8183        iomodel->FetchDataToInput(inputs,elements,"md.initialization.vx",VxEnum);
    8284        iomodel->FetchDataToInput(inputs,elements,"md.initialization.vy",VyEnum);
     
    8890   iomodel->FindConstant(&isstochastic,"md.stochasticforcing.isstochasticforcing");
    8991   switch(calvinglaw){
     92
     93                /*"Continuous" calving laws*/
    9094      case DefaultCalvingEnum:
    9195         iomodel->FetchDataToInput(inputs,elements,"md.calving.calvingrate",CalvingCalvingrateEnum);
     
    103107                        iomodel->FetchDataToInput(inputs,elements,"md.geometry.bed",BedEnum);
    104108                        break;
    105                 case CalvingMinthicknessEnum:
    106                         iomodel->FetchDataToInput(inputs,elements,"md.geometry.bed",BedEnum);
    107                         break;
    108                 case CalvingHabEnum:
    109                         iomodel->FetchDataToInput(inputs,elements,"md.calving.flotation_fraction",CalvingHabFractionEnum);
    110                         break;
    111                 case CalvingCrevasseDepthEnum:
    112                         iomodel->FetchDataToInput(inputs,elements,"md.calving.water_height",WaterheightEnum);
    113                         break;
    114109                case CalvingDev2Enum:
    115110                        iomodel->FetchDataToInput(inputs,elements,"md.calving.stress_threshold_groundedice",CalvingStressThresholdGroundediceEnum);
    116111                        iomodel->FetchDataToInput(inputs,elements,"md.calving.stress_threshold_floatingice",CalvingStressThresholdFloatingiceEnum);
    117112                        break;
     113                case CalvingTestEnum:
     114                        break;
     115                case CalvingParameterizationEnum:
     116                        iomodel->FetchDataToInput(inputs,elements,"md.calving.stress_threshold_groundedice",CalvingStressThresholdGroundediceEnum);
     117                        iomodel->FetchDataToInput(inputs,elements,"md.calving.stress_threshold_floatingice",CalvingStressThresholdFloatingiceEnum);
     118                        iomodel->FetchDataToInput(inputs,elements,"md.geometry.bed",BedEnum);
     119                        break;
     120
     121                /*"Discrete" calving laws (need to specify rate as 0 so that we can still solve the level set equation)*/
     122                case CalvingMinthicknessEnum:
     123                        iomodel->FetchDataToInput(inputs,elements,"md.geometry.bed",BedEnum);
     124                        iomodel->ConstantToInput(inputs,elements,0.,CalvingratexEnum,P1Enum);
     125                        iomodel->ConstantToInput(inputs,elements,0.,CalvingrateyEnum,P1Enum);
     126                        break;
     127                case CalvingHabEnum:
     128                        iomodel->FetchDataToInput(inputs,elements,"md.calving.flotation_fraction",CalvingHabFractionEnum);
     129                        iomodel->ConstantToInput(inputs,elements,0.,CalvingratexEnum,P1Enum);
     130                        iomodel->ConstantToInput(inputs,elements,0.,CalvingrateyEnum,P1Enum);
     131                        break;
     132                case CalvingCrevasseDepthEnum:
     133                        iomodel->FetchDataToInput(inputs,elements,"md.calving.water_height",WaterheightEnum);
     134                        iomodel->ConstantToInput(inputs,elements,0.,CalvingratexEnum,P1Enum);
     135                        iomodel->ConstantToInput(inputs,elements,0.,CalvingrateyEnum,P1Enum);
     136                        break;
     137
    118138                default:
    119139                        _error_("Calving law "<<EnumToStringx(calvinglaw)<<" not supported yet");
     
    126146                case FrontalForcingsDefaultEnum:
    127147                        iomodel->FetchDataToInput(inputs,elements,"md.frontalforcings.meltingrate",CalvingMeltingrateEnum);
     148                        if (calvinglaw == CalvingParameterizationEnum) {
     149                                iomodel->FetchDataToInput(inputs,elements,"md.frontalforcings.ablationrate",CalvingAblationrateEnum);
     150                        }
    128151                        break;
    129152                case FrontalForcingsRignotEnum:
     
    148171
    149172        int  calvinglaw;
     173   IssmDouble *transparam = NULL;
     174   IssmDouble  yts;
     175   int         N,M;
     176   bool        interp,cycle;
     177
    150178        iomodel->FindConstant(&calvinglaw,"md.calving.law");
    151179        switch(calvinglaw){
     
    168196                        parameters->AddObject(iomodel->CopyConstantObject("md.calving.height_above_floatation",CalvingHeightAboveFloatationEnum));
    169197                        break;
     198                case CalvingTestEnum:
     199                        iomodel->FindConstant(&interp,"md.timestepping.interp_forcing");
     200                        iomodel->FindConstant(&cycle,"md.timestepping.cycle_forcing");
     201                        iomodel->FetchData(&transparam,&N,&M,"md.calving.speedfactor");
     202                        if(N==1){
     203                                _assert_(M==1);
     204                                parameters->AddObject(new DoubleParam(CalvingTestSpeedfactorEnum,transparam[0]));
     205         }
     206         else{
     207            _assert_(N==2);
     208            parameters->AddObject(new TransientParam(CalvingTestSpeedfactorEnum,&transparam[0],&transparam[M],interp,cycle,M));
     209         }
     210                        xDelete<IssmDouble>(transparam);
     211                        iomodel->FetchData(&transparam,&N,&M,"md.calving.independentrate");
     212                        if(N==1){
     213                                _assert_(M==1);
     214                                parameters->AddObject(new DoubleParam(CalvingTestIndependentRateEnum,transparam[0]));
     215         }
     216         else{
     217            _assert_(N==2);
     218            parameters->AddObject(new TransientParam(CalvingTestIndependentRateEnum,&transparam[0],&transparam[M],interp,cycle,M));
     219         }
     220                        xDelete<IssmDouble>(transparam);
     221                        break;
     222                case CalvingParameterizationEnum:
     223                        parameters->AddObject(iomodel->CopyConstantObject("md.calving.min_thickness",CalvingMinthicknessEnum));
     224                        parameters->AddObject(iomodel->CopyConstantObject("md.calving.use_param",CalvingUseParamEnum));
     225                        parameters->AddObject(iomodel->CopyConstantObject("md.calving.scale_theta",CalvingScaleThetaEnum));
     226                        parameters->AddObject(iomodel->CopyConstantObject("md.calving.amp_alpha",CalvingAmpAlphaEnum));
     227                        parameters->AddObject(iomodel->CopyConstantObject("md.calving.midp",CalvingMidpointEnum));
     228                        parameters->AddObject(iomodel->CopyConstantObject("md.calving.nonlinearlaw",CalvingNonlinearLawEnum));
     229                        break;
    170230                default:
    171231                        _error_("Calving law "<<EnumToStringx(calvinglaw)<<" not supported yet");
     
    175235        int melt_parameterization;
    176236        iomodel->FindConstant(&melt_parameterization,"md.frontalforcings.parameterization");
    177         int M,N;
    178         IssmDouble* transparam = NULL;
    179237        switch(melt_parameterization){
    180238                case FrontalForcingsDefaultEnum:
     
    209267        /*parameters: */
    210268        int  stabilization;
    211         bool save_results;
    212         femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
    213269        femmodel->parameters->FindParam(&stabilization,LevelsetStabilizationEnum);
    214270
     
    222278        else{
    223279                solutionsequence_linear(femmodel);
    224         }
    225 
    226         if(save_results){
    227                 int outputs[1] = {MaskIceLevelsetEnum};
    228                 femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],1);
    229280        }
    230281}/*}}}*/
     
    400451                                break;
    401452                        }
     453                        case 6:{
     454                                /*SUPG*/
     455                                IssmDouble vx,vy;
     456                                mf_vx_input->GetInputAverage(&vx);
     457                                mf_vy_input->GetInputAverage(&vy);
     458                                vel=sqrt(vx*vx+vy*vy)+1.e-8;
     459                                IssmDouble ECN, K;
     460                                ECN = vel *dt /h;
     461                                K = 1./tanh(ECN) - 1./ECN;
     462//                              if (ECN<1e-6) K = ECN /3.0;
     463
     464                                /*According to Hilmar, xi=K is too large*/
     465                                IssmDouble xi=0.1*K;
     466
     467                                IssmDouble  tau=xi*h/(2*vel);
     468                                Input* levelset_input = NULL;
     469
     470
     471                                IssmDouble kappa;
     472                                IssmDouble p=4, q=4;
     473                                IssmDouble phi[3];
     474
     475                           levelset_input=basalelement->GetInput(MaskIceLevelsetEnum); _assert_(levelset_input);
     476                                levelset_input->GetInputValue(&phi[0], gauss);
     477
     478                                IssmDouble dphidx=0., dphidy=0.;
     479                                IssmDouble nphi;
     480
     481                                for(int i=0;i<numnodes;i++){
     482                                        dphidx += phi[i]*dbasis[0*numnodes+i];
     483                                        dphidy += phi[i]*dbasis[1*numnodes+i];
     484                                }
     485                                nphi = sqrt(dphidx*dphidx+dphidy*dphidy);
     486                       
     487                                if (nphi >= 1) {
     488                                        kappa = 1 - 1.0/nphi;
     489                                }
     490                                else {
     491                                        kappa = 0.5/M_PI *sin(2*M_PI*nphi)/nphi;
     492                                }
     493
     494                                kappa = kappa * vel / h;
     495
     496                                /*Mass matrix - part 2*/
     497                                for(int i=0;i<numnodes;i++){
     498                                        for(int j=0;j<numnodes;j++){
     499                                                Ke->values[i*numnodes+j]+=gauss->weight*Jdet*tau*basis[j]*(vx*dbasis[0*numnodes+i]+vy*dbasis[1*numnodes+i]);
     500                                        }
     501                                }
     502
     503                                /*Advection matrix - part 2, A*/
     504                                for(int i=0;i<numnodes;i++){
     505                                        for(int j=0;j<numnodes;j++){
     506                                                Ke->values[i*numnodes+j]+=dt*gauss->weight*Jdet*tau*(vx*dbasis[0*numnodes+j]+vy*dbasis[1*numnodes+j])*(vx*dbasis[0*numnodes+i]+vy*dbasis[1*numnodes+i]);
     507                                        }
     508                                }
     509                                /*Add the pertubation term \nabla\cdot(\kappa*\nabla\phi)*/
     510                                for(int i=0;i<numnodes;i++){
     511                                        for(int j=0;j<numnodes;j++){
     512                                                for(int k=0;k<dim;k++){
     513                                                                Ke->values[i*numnodes+j]+= dt*gauss->weight*Jdet*kappa*dbasis[k*numnodes+j]*dbasis[k*numnodes+i];
     514                                                }
     515                                        }
     516                                }
     517
     518                                break;
     519                        }
    402520                        default:
    403521                                _error_("unknown type of stabilization in LevelsetAnalysis.cpp");
     
    435553        IssmDouble*    basis = xNew<IssmDouble>(numnodes);
    436554        IssmDouble*    dbasis = NULL;
    437         if(stabilization==5) dbasis= xNew<IssmDouble>(2*numnodes);
     555        if((stabilization==5) |(stabilization == 6)) dbasis= xNew<IssmDouble>(2*numnodes);
    438556
    439557        /*Retrieve all inputs and parameters*/
     
    456574
    457575                if(stabilization==5){ /*SUPG*/
    458          IssmDouble vx,vy,vel;
     576                        IssmDouble vx,vy,vel;
    459577                        basalelement->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
    460578                        mf_vx_input->GetInputAverage(&vx);
     
    469587                        }
    470588                }
     589                else if (stabilization ==6) {
     590                        IssmDouble vx,vy,vel;
     591                        basalelement->NodalFunctionsDerivatives(dbasis,xyz_list,gauss);
     592                        mf_vx_input->GetInputAverage(&vx);
     593                        mf_vy_input->GetInputAverage(&vy);
     594                        vel=sqrt(vx*vx+vy*vy)+1.e-8;
     595
     596                        IssmDouble ECN, K;
     597                        ECN = vel *dt /h;
     598                        K = 1./tanh(ECN) - 1./ECN;
     599        //              if (ECN<1e-6) K = ECN /3.0;
     600
     601                        /*According to Hilmar, xi=K is too large*/
     602                        IssmDouble xi=0.1*K;
     603
     604                        IssmDouble  tau=xi*h/(2*vel);
     605
     606                        /*Force vector - part 2*/
     607                        for(int i=0;i<numnodes;i++){
     608                                pe->values[i]+=Jdet*gauss->weight*lsf*tau*(vx*dbasis[0*numnodes+i]+vy*dbasis[1*numnodes+i]);
     609                        }
     610                }
    471611        }
    472612
     
    474614        xDelete<IssmDouble>(xyz_list);
    475615        xDelete<IssmDouble>(basis);
    476    xDelete<IssmDouble>(dbasis);
     616        xDelete<IssmDouble>(dbasis);
    477617        basalelement->FindParam(&domaintype,DomainTypeEnum);
    478618        if(basalelement->IsSpawnedElement()){basalelement->DeleteMaterials(); delete basalelement;};
     
    525665        }
    526666}/*}}}*/
     667void           LevelsetAnalysis::PostProcess(FemModel* femmodel){/*{{{*/
     668
     669        /*This function is only used by "discrete calving laws" for which we change
     670         * the value of the levelset after the advection step (level set equation
     671         * solve) based on the law*/
     672
     673        /*Intermediaries*/
     674        int  calvinglaw;
     675        IssmDouble newlevelset[6];
     676        femmodel->parameters->FindParam(&calvinglaw,CalvingLawEnum);
     677
     678        /*Apply minimum thickness criterion*/
     679        if(calvinglaw==CalvingMinthicknessEnum || calvinglaw==CalvingVonmisesEnum || calvinglaw==CalvingParameterizationEnum){
     680
     681                IssmDouble mig_max = femmodel->parameters->FindParam(MigrationMaxEnum);
     682                IssmDouble dt      = femmodel->parameters->FindParam(TimesteppingTimeStepEnum);
     683
     684                /*Get current distance to terminus*/
     685                InputDuplicatex(femmodel,MaskIceLevelsetEnum,DistanceToCalvingfrontEnum);
     686                femmodel->DistanceToFieldValue(MaskIceLevelsetEnum,0,DistanceToCalvingfrontEnum);
     687
     688                /*Intermediaries*/
     689                IssmDouble thickness,bed,sealevel,distance,levelset;
     690                IssmDouble min_thickness = femmodel->parameters->FindParam(CalvingMinthicknessEnum);
     691
     692                /*Loop over all elements of this partition*/
     693                for(Object* & object : femmodel->elements->objects){
     694                        Element* element  = xDynamicCast<Element*>(object);
     695
     696                        /*no need to postprocess an ice free element*/
     697                        if(!element->IsIceInElement()) continue;
     698
     699                        int      numnodes     = element->GetNumberOfNodes(); _assert_(numnodes<7);
     700                        Gauss*   gauss        = element->NewGauss();
     701                        Input *H_input        = element->GetInput(ThicknessEnum);              _assert_(H_input);
     702                        Input *b_input        = element->GetInput(BedEnum);                    _assert_(b_input);
     703                        Input *sl_input       = element->GetInput(SealevelEnum);               _assert_(sl_input);
     704                        Input *dis_input      = element->GetInput(DistanceToCalvingfrontEnum); _assert_(dis_input);
     705                        Input *levelset_input = element->GetInput(MaskIceLevelsetEnum);        _assert_(levelset_input);
     706
     707                        /*Potentially constrain nodes of this element*/
     708                        for(int in=0;in<numnodes;in++){
     709                                gauss->GaussNode(element->GetElementType(),in);
     710
     711                                levelset_input->GetInputValue(&levelset,gauss);
     712                                H_input->GetInputValue(&thickness,gauss);
     713                                b_input->GetInputValue(&bed,gauss);
     714                                sl_input->GetInputValue(&sealevel,gauss);
     715                                dis_input->GetInputValue(&distance,gauss);
     716
     717                                if(thickness<min_thickness && bed<sealevel && fabs(distance)<mig_max*dt && levelset<0){
     718                                        newlevelset[in] = +400.; //Arbitrary > 0 number (i.e. deactivate this node)
     719                                }
     720                                else{
     721                                        newlevelset[in] = levelset;
     722                                }
     723                        }
     724                        element->AddInput(MaskIceLevelsetEnum,&newlevelset[0],element->GetElementType());
     725                        delete gauss;
     726                }
     727        }
     728}/*}}}*/
    527729void           LevelsetAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
    528730
     
    530732        int  calvinglaw;
    531733        femmodel->parameters->FindParam(&calvinglaw,CalvingLawEnum);
    532 
    533         if(calvinglaw==CalvingMinthicknessEnum || calvinglaw==CalvingVonmisesEnum){
     734        IssmDouble mig_max = femmodel->parameters->FindParam(MigrationMaxEnum);
     735        IssmDouble dt      = femmodel->parameters->FindParam(TimesteppingTimeStepEnum);
     736
     737   /*Get current distance to terminus*/
     738   InputDuplicatex(femmodel,MaskIceLevelsetEnum,DistanceToCalvingfrontEnum);
     739   femmodel->DistanceToFieldValue(MaskIceLevelsetEnum,0,DistanceToCalvingfrontEnum);
     740
     741   if(calvinglaw==CalvingHabEnum){
    534742
    535743                /*Intermediaries*/
    536                 IssmDouble thickness,bed,sealevel;
    537                 IssmDouble min_thickness = femmodel->parameters->FindParam(CalvingMinthicknessEnum);
     744                IssmDouble  thickness,water_depth,distance,hab_fraction;
    538745
    539746                /*Loop over all elements of this partition*/
     
    541748                        Element* element  = xDynamicCast<Element*>(object);
    542749
    543                         int      numnodes = element->GetNumberOfNodes();
    544                         Gauss*   gauss    = element->NewGauss();
    545                         Input*   H_input  = element->GetInput(ThicknessEnum); _assert_(H_input);
    546                         Input*   b_input = element->GetInput(BedEnum); _assert_(b_input);
    547                         Input*   sl_input = element->GetInput(SealevelEnum); _assert_(sl_input);
     750                        IssmDouble rho_ice   = element->FindParam(MaterialsRhoIceEnum);
     751                        IssmDouble rho_water = element->FindParam(MaterialsRhoSeawaterEnum);
     752
     753                        int      numnodes           = element->GetNumberOfNodes();
     754                        Gauss*   gauss              = element->NewGauss();
     755                        Input*   H_input            = element->GetInput(ThicknessEnum); _assert_(H_input);
     756                        Input*   bed_input          = element->GetInput(BedEnum); _assert_(bed_input);
     757                        Input*   hab_fraction_input = element->GetInput(CalvingHabFractionEnum); _assert_(hab_fraction_input);
     758                        Input*   dis_input           = element->GetInput(DistanceToCalvingfrontEnum); _assert_(dis_input);
    548759
    549760                        /*Potentially constrain nodes of this element*/
     
    554765
    555766                                H_input->GetInputValue(&thickness,gauss);
    556                                 b_input->GetInputValue(&bed,gauss);
    557                                 sl_input->GetInputValue(&sealevel,gauss);
    558                                 if(thickness<min_thickness && bed<sealevel){
    559                                         node->ApplyConstraint(0,+1.);
    560                                 }
    561                                 else {
    562                                         /* no ice, set no spc */
    563                                         node->DofInFSet(0);
    564                                 }
    565                         }
    566                         delete gauss;
    567                 }
    568         }
    569    else if(calvinglaw==CalvingHabEnum){
    570 
    571                 /*Intermediaries*/
    572                 IssmDouble  thickness,water_depth,levelset,hab_fraction;
    573 
    574                 /*Get the fraction of the flotation thickness at the terminus*/
    575                 InputDuplicatex(femmodel,MaskIceLevelsetEnum,DistanceToCalvingfrontEnum);
    576                 femmodel->DistanceToFieldValue(MaskIceLevelsetEnum,0,DistanceToCalvingfrontEnum);
    577 
    578                 /*Loop over all elements of this partition*/
    579                 for(Object* & object : femmodel->elements->objects){
    580                         Element* element  = xDynamicCast<Element*>(object);
    581 
    582                         IssmDouble rho_ice   = element->FindParam(MaterialsRhoIceEnum);
    583                         IssmDouble rho_water = element->FindParam(MaterialsRhoSeawaterEnum);
    584 
    585                         int      numnodes           = element->GetNumberOfNodes();
    586                         Gauss*   gauss              = element->NewGauss();
    587                         Input*   H_input            = element->GetInput(ThicknessEnum); _assert_(H_input);
    588                         Input*   bed_input          = element->GetInput(BedEnum); _assert_(bed_input);
    589                         Input*   hab_fraction_input = element->GetInput(CalvingHabFractionEnum); _assert_(hab_fraction_input);
    590                         Input*   ls_input           = element->GetInput(DistanceToCalvingfrontEnum); _assert_(ls_input);
    591 
    592                         /*Potentially constrain nodes of this element*/
    593                         for(int in=0;in<numnodes;in++){
    594                                 gauss->GaussNode(element->GetElementType(),in);
    595                                 Node* node=element->GetNode(in);
    596                                 if(!node->IsActive()) continue;
    597 
    598                                 H_input->GetInputValue(&thickness,gauss);
    599767                                bed_input->GetInputValue(&water_depth,gauss);
    600                                 ls_input->GetInputValue(&levelset,gauss);
     768                                dis_input->GetInputValue(&distance,gauss);
    601769                                hab_fraction_input->GetInputValue(&hab_fraction,gauss);
    602770
    603                                 if(thickness<((rho_water/rho_ice)*(1+hab_fraction)*-water_depth) && levelset>-300. && levelset<0.){
     771                                if(thickness<((rho_water/rho_ice)*(1+hab_fraction)*-water_depth) && fabs(distance)<mig_max*dt){
    604772                                        node->ApplyConstraint(0,+1.);
    605773                                }
     
    628796
    629797                IssmDouble crevasse_threshold = femmodel->parameters->FindParam(CalvingCrevasseThresholdEnum);
    630                 IssmDouble mig_max            = femmodel->parameters->FindParam(MigrationMaxEnum);
    631                 IssmDouble dt                 = femmodel->parameters->FindParam(TimesteppingTimeStepEnum);
     798
    632799
    633800                for(Object* & object : femmodel->elements->objects){
     
    704871                                                surface_input->GetInputValue(&surface,gauss);
    705872
     873                  /*FIXME: not sure about levelset<0. && fabs(levelset)>-mig_max*dt! SHould maybe be distance<mig_max*dt*/
    706874                  if((surface_crevasse>surface || crevassedepth>crevasse_threshold*thickness) && bed<0. && levelset<0. && levelset>-mig_max*dt && constraint_nodes[node->Lid()]==0.){
    707875                                                        local_nflipped++;
  • issm/trunk/src/c/analyses/LevelsetAnalysis.h

    r26744 r27035  
    3232                void           InputUpdateFromSolution(IssmDouble* solution,Element* element);
    3333                void           UpdateConstraints(FemModel* femmodel);
     34
     35                /*Specific methods to LevelsetAnalysis*/
     36                void  PostProcess(FemModel* femmodel);
    3437};
    3538#endif
  • issm/trunk/src/c/analyses/LoveAnalysis.cpp

    r26744 r27035  
    3333        parameters->AddObject(iomodel->CopyConstantObject("md.love.mu0",LoveMu0Enum));
    3434        parameters->AddObject(iomodel->CopyConstantObject("md.love.Gravitational_Constant",LoveGravitationalConstantEnum));
     35        parameters->AddObject(iomodel->CopyConstantObject("md.love.chandler_wobble",LoveChandlerWobbleEnum));
    3536        parameters->AddObject(iomodel->CopyConstantObject("md.love.allow_layer_deletion",LoveAllowLayerDeletionEnum));
    3637        parameters->AddObject(iomodel->CopyConstantObject("md.love.underflow_tol",LoveUnderflowTolEnum));
     38        parameters->AddObject(iomodel->CopyConstantObject("md.love.pw_threshold",LovePostWidderThresholdEnum));
    3739        parameters->AddObject(iomodel->CopyConstantObject("md.love.integration_steps_per_layer",LoveIntStepsPerLayerEnum));
    3840        parameters->AddObject(iomodel->CopyConstantObject("md.love.istemporal",LoveIsTemporalEnum));
     
    4345        parameters->AddObject(iomodel->CopyConstantObject("md.love.core_mantle_boundary",LoveCoreMantleBoundaryEnum));
    4446        parameters->AddObject(iomodel->CopyConstantObject("md.love.complex_computation",LoveComplexComputationEnum));
     47        parameters->AddObject(iomodel->CopyConstantObject("md.solidearth.rotational.equatorialmoi",RotationalEquatorialMoiEnum));
     48        parameters->AddObject(iomodel->CopyConstantObject("md.solidearth.rotational.polarmoi",RotationalPolarMoiEnum));
     49        parameters->AddObject(iomodel->CopyConstantObject("md.solidearth.rotational.angularvelocity",RotationalAngularVelocityEnum));
     50        parameters->AddObject(iomodel->CopyConstantObject("md.solidearth.lovenumbers.tk2secular",TidalLoveK2SecularEnum));
    4551}/*}}}*/
    4652void LoveAnalysis::UpdateConstraints(FemModel* femmodel){/*{{{*/
  • issm/trunk/src/c/analyses/MasstransportAnalysis.cpp

    r26744 r27035  
    182182                        break;
    183183                case SpatialLinearFloatingMeltRateEnum:
    184                         iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_melting_rate",BasalforcingsDeepwaterMeltingRateEnum);
    185                         iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_elevation",BasalforcingsDeepwaterElevationEnum);
    186                         iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.upperwater_elevation",BasalforcingsUpperwaterElevationEnum);
     184                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_melting_rate",BasalforcingsSpatialDeepwaterMeltingRateEnum);
     185                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_elevation",BasalforcingsSpatialDeepwaterElevationEnum);
     186                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.upperwater_melting_rate",BasalforcingsSpatialUpperwaterMeltingRateEnum);
     187                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.upperwater_elevation",BasalforcingsSpatialUpperwaterElevationEnum);
     188                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.perturbation_melting_rate",BasalforcingsPerturbationMeltingRateEnum,0.);
     189                        if(isstochastic){
     190            iomodel->FetchDataToInput(inputs,elements,"md.stochasticforcing.default_id",StochasticForcingDefaultIdEnum);
     191            iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_melting_rate",BaselineBasalforcingsSpatialDeepwaterMeltingRateEnum);
     192         }
    187193                        break;
    188194                case BasalforcingsPicoEnum:
     
    212218                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.ocean_salinity",BasalforcingsOceanSalinityEnum);
    213219                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.ocean_temp",BasalforcingsOceanTempEnum);
     220                        break;
     221                case AutoregressionLinearFloatingMeltRateEnum:
     222                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.basin_id",BasalforcingsLinearBasinIdEnum);
     223                        if(isstochastic) iomodel->FetchDataToInput(inputs,elements,"md.stochasticforcing.default_id",StochasticForcingDefaultIdEnum);
    214224                        break;
    215225                default:
  • issm/trunk/src/c/analyses/SamplingAnalysis.cpp

    r26744 r27035  
    7676  iomodel->FetchDataToInput(inputs,elements,"md.sampling.kappa",SamplingKappaEnum);
    7777        iomodel->FetchDataToInput(inputs,elements,"md.sampling.beta",SamplingBetaEnum,0.);
     78        iomodel->FetchDataToInput(inputs,elements,"md.sampling.tau",SamplingTauEnum);
    7879        iomodel->FetchDataToInput(inputs,elements,"md.initialization.sample",SampleEnum,0.);
     80        iomodel->FetchDataToInput(inputs,elements,"md.initialization.sample",SampleNoiseEnum,0.);
     81        if(iomodel->solution_enum==TransientSolutionEnum) iomodel->FetchDataToInput(inputs,elements,"md.sampling.phi",SamplingPhiEnum,0.);
    7982
    8083}/*}}}*/
     
    8487        char**  requestedoutputs = NULL;
    8588
    86         parameters->AddObject(iomodel->CopyConstantObject("md.sampling.tau",SamplingTauEnum));
    8789        parameters->AddObject(iomodel->CopyConstantObject("md.sampling.alpha",SamplingAlphaEnum));
    8890        parameters->AddObject(iomodel->CopyConstantObject("md.sampling.robin",SamplingRobinEnum));
    89         if(solution_enum==TransientSolutionEnum) parameters->AddObject(iomodel->CopyConstantObject("md.sampling.phi",SamplingPhiEnum));
    9091        parameters->AddObject(iomodel->CopyConstantObject("md.sampling.seed",SamplingSeedEnum));
    9192
     
    273274    element->GetDofListLocal(&doflist,NoneApproximationEnum,GsetEnum);
    274275    IssmDouble* newsample = xNew<IssmDouble>(numnodes);
     276                IssmDouble* tau = xNew<IssmDouble>(numnodes);
     277                element->GetInputListOnNodes(&tau[0],SamplingTauEnum);
    275278
    276279    /*Use the dof list to index into the solution vector: */
    277280    for(int i=0;i<numnodes;i++){
    278                         newsample[i]=solution[doflist[i]];
     281                        newsample[i]=solution[doflist[i]] / tau[i]; // new
     282
    279283                        /*Check solution*/
    280284                        if(xIsNan<IssmDouble>(newsample[i])) _error_("NaN found in solution vector");
     
    287291    /*Free ressources:*/
    288292    xDelete<IssmDouble>(newsample);
     293                xDelete<IssmDouble>(tau);
    289294    xDelete<int>(doflist);
    290295 }/*}}}*/
     
    418423        *pMff=Mff;
    419424}/*}}}*/
     425void                                            SamplingAnalysis::UpdateTransientSample(FemModel *      femmodel){
     426
     427        for(int j=0;j<femmodel->elements->Size();j++){
     428                        Element* element=(Element*)femmodel->elements->GetObjectByOffset(j);
     429                        UpdateTransientSample(element);
     430         }
     431
     432}
     433void                                            SamplingAnalysis::UpdateTransientSample(Element *       element){
     434
     435        /*Intermediaries */
     436        IssmDouble phi, sample, noise;
     437
     438        /*Fetch number vertices for this element*/
     439        int numvertices = element->GetNumberOfVertices();
     440
     441        /*Initialize new sample*/
     442        IssmDouble* sample_new = xNew<IssmDouble>(numvertices);
     443
     444        /*Retrieve all inputs and parameters*/
     445        Input*  sample_input=element->GetInput(SampleOldEnum); _assert_(sample_input);
     446        Input*  noise_input=element->GetInput(SampleNoiseEnum); _assert_(noise_input);
     447        Input*  phi_input=element->GetInput(SamplingPhiEnum); _assert_(phi_input);
     448
     449        /* Start  looping on the number of gaussian points: */
     450        Gauss* gauss=element->NewGauss();
     451  for(int iv=0;iv<numvertices;iv++){
     452        gauss->GaussVertex(iv);
     453
     454                /*Get input values at gauss points*/
     455                sample_input->GetInputValue(&sample,gauss);
     456                noise_input->GetInputValue(&noise,gauss);
     457                phi_input->GetInputValue(&phi,gauss);
     458
     459                /*Get new sample*/
     460                sample_new[iv] = phi*sample + noise;
     461
     462  }
     463
     464  element->AddInput(SampleEnum,sample_new,element->GetElementType());
     465
     466  /*Clean up and return*/
     467  xDelete<IssmDouble>(sample_new);
     468  delete gauss;
     469
     470}
  • issm/trunk/src/c/analyses/SamplingAnalysis.h

    r26744 r27035  
    4040                void           MassMatrix(Matrix<IssmDouble>** pMff,FemModel* femmodel);
    4141
     42                void                                    UpdateTransientSample(FemModel* femmodel);
     43                void                                    UpdateTransientSample(Element *         element);
     44
    4245};
    4346#endif
  • issm/trunk/src/c/analyses/SealevelchangeAnalysis.cpp

    r26744 r27035  
    8585        IssmDouble* love_tk=NULL;
    8686        IssmDouble* love_tl=NULL;
     87        IssmDouble* love_pmtf_colinear=NULL;
     88        IssmDouble* love_pmtf_ortho=NULL;
    8789        IssmDouble* love_timefreq=NULL;
    8890        bool        love_istime=true;
     
    101103        IssmDouble* H_viscoelastic_interpolated= NULL;
    102104        IssmDouble* H_viscoelastic_local = NULL;
     105        IssmDouble* Pmtf_col_interpolated = NULL;
     106        IssmDouble* Pmtf_ortho_interpolated = NULL;
     107        IssmDouble* Pmtf_z_interpolated = NULL;
     108        IssmDouble* Love_th2_interpolated = NULL;
     109        IssmDouble* Love_tk2_interpolated = NULL;
     110        IssmDouble* Love_tl2_interpolated = NULL;
     111
    103112        int         M,m,lower_row,upper_row;
    104113        IssmDouble  degacc=.01;
     
    166175        /*compute planet area and plug into parameters:*/
    167176        iomodel->FetchData(&planetradius,"md.solidearth.planetradius");
    168         planetarea=4*PI*planetradius*planetradius;
     177        planetarea=4*M_PI*planetradius*planetradius;
    169178        parameters->AddObject(new DoubleParam(SolidearthPlanetAreaEnum,planetarea));
    170179
     
    253262                        iomodel->FetchData(&love_k,&ndeg,&precomputednt,"md.solidearth.lovenumbers.k");
    254263                        iomodel->FetchData(&love_l,&ndeg,&precomputednt,"md.solidearth.lovenumbers.l");
    255                         iomodel->FetchData(&love_th,&ndeg,&precomputednt,"md.solidearth.lovenumbers.th");
    256                         iomodel->FetchData(&love_tk,&ndeg,&precomputednt,"md.solidearth.lovenumbers.tk");
    257                         iomodel->FetchData(&love_tl,&ndeg,&precomputednt,"md.solidearth.lovenumbers.tl");
    258264
    259265                        parameters->AddObject(new DoubleParam(SolidearthSettingsTimeAccEnum,timeacc));
     
    261267                        parameters->AddObject(new DoubleMatParam(LoadLoveKEnum,love_k,ndeg,precomputednt));
    262268                        parameters->AddObject(new DoubleMatParam(LoadLoveLEnum,love_l,ndeg,precomputednt));
    263                         parameters->AddObject(new DoubleMatParam(TidalLoveHEnum,love_th,ndeg,precomputednt));
    264                         parameters->AddObject(new DoubleMatParam(TidalLoveKEnum,love_tk,ndeg,precomputednt));
    265                         parameters->AddObject(new DoubleMatParam(TidalLoveLEnum,love_tl,ndeg,precomputednt));
     269
     270                        if (rotation){
     271                                iomodel->FetchData(&love_th,&ndeg,&precomputednt,"md.solidearth.lovenumbers.th");
     272                                iomodel->FetchData(&love_tk,&ndeg,&precomputednt,"md.solidearth.lovenumbers.tk");
     273                                iomodel->FetchData(&love_tl,&ndeg,&precomputednt,"md.solidearth.lovenumbers.tl");
     274                                iomodel->FetchData(&love_pmtf_colinear,&dummy,&precomputednt,"md.solidearth.lovenumbers.pmtf_colinear");
     275                                iomodel->FetchData(&love_pmtf_ortho,&dummy,&precomputednt,"md.solidearth.lovenumbers.pmtf_ortho");
     276
     277                                parameters->AddObject(new DoubleMatParam(LovePolarMotionTransferFunctionColinearEnum,love_pmtf_colinear,1,precomputednt));
     278                                parameters->AddObject(new DoubleMatParam(LovePolarMotionTransferFunctionOrthogonalEnum,love_pmtf_ortho,1,precomputednt));
     279                                parameters->AddObject(new DoubleMatParam(TidalLoveHEnum,love_th,ndeg,precomputednt));
     280                                parameters->AddObject(new DoubleMatParam(TidalLoveKEnum,love_tk,ndeg,precomputednt));
     281                                parameters->AddObject(new DoubleMatParam(TidalLoveLEnum,love_tl,ndeg,precomputednt));
     282                        }
     283
    266284                        parameters->AddObject(new DoubleMatParam(LoveTimeFreqEnum,love_timefreq,precomputednt,1));
    267285                        parameters->AddObject(new BoolParam(LoveIsTimeEnum,love_istime));
     
    283301                                parameters->AddObject(new IntParam(SealevelchangeViscousIndexEnum,0));
    284302                                xDelete<IssmDouble>(viscoustimes);
     303                                if (rotation){
     304                                        IssmDouble* viscouspolarmotion=NULL;
     305                                        viscouspolarmotion=xNewZeroInit<IssmDouble>(3*nt);
     306                                        parameters->AddObject(new DoubleMatParam(SealevelchangeViscousPolarMotionEnum,viscouspolarmotion,3,nt));
     307                                        xDelete<IssmDouble>(viscouspolarmotion);
     308                                }
    285309                        }
    286310                        else {
     
    307331                }
    308332
    309                 if(rotation)parameters->AddObject(iomodel->CopyConstantObject("md.solidearth.lovenumbers.tk2secular",TidalLoveK2SecularEnum));
    310 
     333                if(rotation) parameters->AddObject(iomodel->CopyConstantObject("md.solidearth.lovenumbers.tk2secular",TidalLoveK2SecularEnum));
    311334                if(selfattraction){
    312335
    313                         /*compute combined legendre + love number (elastic green function:*/
     336                        /*compute combined legendre + love number (elastic green function):*/
    314337                        m=DetermineLocalSize(M,IssmComm::GetComm());
    315338                        GetOwnershipBoundariesFromRange(&lower_row,&upper_row,m,IssmComm::GetComm());
     
    441464                                U_viscoelastic_interpolated=xNew<IssmDouble>(M*nt,"t");
    442465                                if(horiz)H_viscoelastic_interpolated=xNew<IssmDouble>(M*nt,"t");
     466                                if(rotation){
     467                                        Pmtf_col_interpolated=xNew<IssmDouble>(nt,"t");
     468                                        Pmtf_ortho_interpolated=xNew<IssmDouble>(nt,"t");
     469                                        Pmtf_z_interpolated=xNew<IssmDouble>(nt,"t");
     470                                        Love_tk2_interpolated=xNew<IssmDouble>(nt,"t");
     471                                        Love_th2_interpolated=xNew<IssmDouble>(nt,"t");
     472                                        if (horiz) Love_tl2_interpolated=xNew<IssmDouble>(nt,"t");
     473                                }
    443474#else
    444475                                G_viscoelastic_interpolated=xNew<IssmDouble>(M*nt);
    445476                                U_viscoelastic_interpolated=xNew<IssmDouble>(M*nt);
    446477                                if(horiz)H_viscoelastic_interpolated=xNew<IssmDouble>(M*nt);
     478                                if(rotation){
     479                                        Pmtf_col_interpolated=xNew<IssmDouble>(nt);
     480                                        Pmtf_ortho_interpolated=xNew<IssmDouble>(nt);
     481                                        Pmtf_z_interpolated=xNew<IssmDouble>(nt);
     482                                        Love_tk2_interpolated=xNew<IssmDouble>(nt);
     483                                        Love_th2_interpolated=xNew<IssmDouble>(nt);
     484                                        if (horiz) Love_tl2_interpolated=xNew<IssmDouble>(nt);
     485                                }
    447486#endif
    448487
     
    477516                                                if(horiz)H_viscoelastic_interpolated[timeindex]=(1-lincoeff)*H_viscoelastic[timepreindex]+lincoeff*H_viscoelastic[timepreindex+1];
    478517                                        }
     518
     519                                        if(rotation){
     520                                                int timepreindex= 2*precomputednt+timeindex2;
     521                                                Pmtf_col_interpolated[t]=(1.0-lincoeff)*love_pmtf_colinear[timeindex2]+lincoeff*love_pmtf_colinear[timeindex2+1];
     522                                                Pmtf_ortho_interpolated[t]=(1.0-lincoeff)*love_pmtf_ortho[timeindex2]+lincoeff*love_pmtf_ortho[timeindex2+1];
     523                                                Pmtf_z_interpolated[t]=1.0+(1.0-lincoeff)*love_k[timepreindex]+lincoeff*love_k[timepreindex+1];
     524                                                Love_tk2_interpolated[t]=(1.0-lincoeff)*love_tk[timepreindex]+lincoeff*love_tk[timepreindex+1];
     525                                                Love_th2_interpolated[t]=(1.0-lincoeff)*love_th[timepreindex]+lincoeff*love_th[timepreindex+1];
     526                                                if (horiz) Love_tl2_interpolated[t]=(1.0-lincoeff)*love_tl[timepreindex]+lincoeff*love_tl[timepreindex+1];
     527                                        }
    479528                                }
    480529
     
    491540                                if(horiz)H_viscoelastic_interpolated=H_viscoelastic;
    492541#endif
     542
     543                                if(rotation){ //if this cpu handles degree 2
     544#ifdef _HAVE_AD_
     545                                        Pmtf_col_interpolated=xNew<IssmDouble>(1,"t");
     546                                        Pmtf_ortho_interpolated=xNew<IssmDouble>(1,"t");
     547                                        Pmtf_z_interpolated=xNew<IssmDouble>(1,"t");
     548                                        Love_tk2_interpolated=xNew<IssmDouble>(1,"t");
     549                                        Love_th2_interpolated=xNew<IssmDouble>(1,"t");
     550                                        if (horiz) Love_tl2_interpolated=xNew<IssmDouble>(1,"t");
     551#else
     552                                        Pmtf_col_interpolated=xNew<IssmDouble>(1);
     553                                        Pmtf_ortho_interpolated=xNew<IssmDouble>(1);
     554                                        Pmtf_z_interpolated=xNew<IssmDouble>(1);
     555                                        Love_tk2_interpolated=xNew<IssmDouble>(1);
     556                                        Love_th2_interpolated=xNew<IssmDouble>(1);
     557                                        if (horiz) Love_tl2_interpolated=xNew<IssmDouble>(1);
     558#endif
     559
     560                                        Pmtf_col_interpolated=love_pmtf_colinear;
     561                                        Pmtf_ortho_interpolated=love_pmtf_ortho;
     562                                        Pmtf_z_interpolated[0]=1.0+love_k[2];
     563                                        Love_tk2_interpolated[0]=love_tk[2];
     564                                        Love_th2_interpolated[0]=love_th[2];
     565                                        if (horiz) Love_tl2_interpolated[0]=love_tl[2];
     566                                }
    493567                        }       
    494568
     
    499573                                parameters->AddObject(new DoubleVecParam(SealevelchangeUViscoElasticEnum,U_viscoelastic_interpolated,M*nt));
    500574                                if(horiz)parameters->AddObject(new DoubleVecParam(SealevelchangeHViscoElasticEnum,H_viscoelastic_interpolated,M*nt));
     575                                if(rotation){
     576                                        parameters->AddObject(new DoubleVecParam(SealevelchangePolarMotionTransferFunctionColinearEnum,Pmtf_col_interpolated,nt));
     577                                        parameters->AddObject(new DoubleVecParam(SealevelchangePolarMotionTransferFunctionOrthogonalEnum,Pmtf_ortho_interpolated,nt));
     578                                        parameters->AddObject(new DoubleVecParam(SealevelchangePolarMotionTransferFunctionZEnum,Pmtf_z_interpolated,nt));
     579                                        parameters->AddObject(new DoubleVecParam(SealevelchangeTidalH2Enum,Love_th2_interpolated,nt));
     580                                        parameters->AddObject(new DoubleVecParam(SealevelchangeTidalK2Enum,Love_tk2_interpolated,nt));
     581                                        if (horiz) parameters->AddObject(new DoubleVecParam(SealevelchangeTidalL2Enum,Love_tl2_interpolated,nt));
     582                                }
    501583                        }
    502584
     
    519601                                        xDelete<IssmDouble>(H_viscoelastic_local);
    520602                                }
     603                                if(rotation){
     604                                        xDelete<IssmDouble>(love_pmtf_colinear);
     605                                        xDelete<IssmDouble>(love_pmtf_ortho);
     606
     607                                }
    521608                        }
    522609                } /*}}}*/
     
    545632        iomodel->DeleteData(&requestedoutputs,numoutputs,"md.solidearth.requested_outputs");
    546633        /*}}}*/
    547 
    548634}/*}}}*/
    549635
  • issm/trunk/src/c/analyses/SmbAnalysis.cpp

    r26744 r27035  
    2424
    2525        int    smb_model;
    26         bool   isdelta18o,ismungsm,isd18opd,issetpddfac,isprecipscaled,istemperaturescaled,isfirnwarming;
     26        bool   isdelta18o,ismungsm,isd18opd,issetpddfac,isprecipscaled,istemperaturescaled,isfirnwarming,isstochastic;
    2727
    2828        /*Update elements: */
     
    3838        /*Figure out smb model: */
    3939        iomodel->FindConstant(&smb_model,"md.smb.model");
     40        iomodel->FindConstant(&isstochastic,"md.stochasticforcing.isstochasticforcing");
    4041        switch(smb_model){
    4142                case SMBforcingEnum:
    4243                        iomodel->FetchDataToInput(inputs,elements,"md.smb.mass_balance",SmbMassBalanceEnum,0.);
     44                        if(isstochastic){
     45                                iomodel->FetchDataToInput(inputs,elements,"md.stochasticforcing.default_id",StochasticForcingDefaultIdEnum);
     46                                iomodel->FetchDataToInput(inputs,elements,"md.smb.mass_balance",BaselineSmbMassBalanceEnum,0.);
     47                        }
    4348                        break;
    4449                case SMBgembEnum:
  • issm/trunk/src/c/analyses/StressbalanceAnalysis.cpp

    r26744 r27035  
    3131        IssmDouble rho_ice;
    3232        IssmDouble FSreconditioning;
    33         bool       isSIA,isSSA,isL1L2,isMLHO,isHO,isFS,iscoupling;
     33        bool       isSIA,isSSA,isL1L2,isMOLHO,isHO,isFS,iscoupling;
    3434        bool       spcpresent = false;
    3535        int        Mx,Nx;
     
    5959        iomodel->FindConstant(&isSSA,"md.flowequation.isSSA");
    6060        iomodel->FindConstant(&isL1L2,"md.flowequation.isL1L2");
    61         iomodel->FindConstant(&isMLHO,"md.flowequation.isMLHO");
     61        iomodel->FindConstant(&isMOLHO,"md.flowequation.isMOLHO");
    6262        iomodel->FindConstant(&isHO,"md.flowequation.isHO");
    6363        iomodel->FindConstant(&isFS,"md.flowequation.isFS");
    6464
    6565        /*Is this model only SIA??*/
    66         if(!isSSA && !isHO && !isFS && !isL1L2 && !isMLHO) return;
     66        if(!isSSA && !isHO && !isFS && !isL1L2 && !isMOLHO) return;
    6767
    6868        /*Do we have coupling*/
    69         if((isSIA?1.:0.) + (isSSA?1.:0.) + (isL1L2?1.:0.) + (isMLHO?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
     69        if((isSIA?1.:0.) + (isSSA?1.:0.) + (isL1L2?1.:0.) + (isMOLHO?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
    7070         iscoupling = true;
    7171        else
     
    7878                if(isSSA)       iomodel->FindConstant(&finiteelement,"md.flowequation.fe_SSA");
    7979                else if(isL1L2) finiteelement = P1Enum;
    80                 else if(isMLHO) finiteelement = P1Enum;
     80                else if(isMOLHO) finiteelement = P1Enum;
    8181                else if(isHO)   iomodel->FindConstant(&finiteelement,"md.flowequation.fe_HO");
    8282                else if(isFS){  iomodel->FindConstant(&finiteelement,"md.flowequation.fe_FS");
     
    188188                }
    189189                else{
    190                         if(!isMLHO){
     190                        if(!isMOLHO){
    191191                                IoModelToConstraintsx(constraints,iomodel,"md.stressbalance.spcvx",StressbalanceAnalysisEnum,finiteelement,0);
    192192                                if(iomodel->domaintype!=Domain2DverticalEnum){
     
    194194                                }
    195195                        }
    196                         else{//MLHO
     196                        else{//MOLHO
    197197                                IoModelToConstraintsx(constraints,iomodel,"md.stressbalance.spcvx_base",StressbalanceAnalysisEnum,finiteelement,0);
    198198                                IoModelToConstraintsx(constraints,iomodel,"md.stressbalance.spcvx_shear",StressbalanceAnalysisEnum,finiteelement,1);
     
    462462        int         count;
    463463        int         penpair_ids[2];
    464         bool        isSSA,isL1L2,isMLHO,isHO,isFS;
     464        bool        isSSA,isL1L2,isMOLHO,isHO,isFS;
    465465        int         numpenalties,numrifts,numriftsegments;
    466466        IssmDouble *riftinfo       = NULL;
     
    470470        /*Fetch parameters: */
    471471        iomodel->FindConstant(&isL1L2,"md.flowequation.isL1L2");
    472         iomodel->FindConstant(&isMLHO,"md.flowequation.isMLHO");
     472        iomodel->FindConstant(&isMOLHO,"md.flowequation.isMOLHO");
    473473        iomodel->FindConstant(&isFS,"md.flowequation.isFS");
    474474        iomodel->FindConstant(&isSSA,"md.flowequation.isSSA");
     
    477477
    478478        /*Is this SIA only?*/
    479         if(!isSSA && !isHO && !isFS && !isL1L2 && !isMLHO) return;
     479        if(!isSSA && !isHO && !isFS && !isL1L2 && !isMOLHO) return;
    480480
    481481        /*Initialize counter: */
     
    522522
    523523        /*Intermediary*/
    524         bool isSSA,isL1L2,isMLHO,isHO,isFS,iscoupling;
     524        bool isSSA,isL1L2,isMOLHO,isHO,isFS,iscoupling;
    525525        int  finiteelement=-1,approximation=-1;
    526526
     
    528528        iomodel->FindConstant(&isSSA,"md.flowequation.isSSA");
    529529        iomodel->FindConstant(&isL1L2,"md.flowequation.isL1L2");
    530         iomodel->FindConstant(&isMLHO,"md.flowequation.isMLHO");
     530        iomodel->FindConstant(&isMOLHO,"md.flowequation.isMOLHO");
    531531        iomodel->FindConstant(&isHO,"md.flowequation.isHO");
    532532        iomodel->FindConstant(&isFS,"md.flowequation.isFS");
    533533
    534534        /*Now, check that we have non SIA elements */
    535         if(!isSSA && !isL1L2 && !isMLHO && !isHO && !isFS) return;
     535        if(!isSSA && !isL1L2 && !isMOLHO && !isHO && !isFS) return;
    536536
    537537        /*Do we have coupling*/
    538         if( (isSSA?1.:0.) + (isL1L2?1.:0.) + (isMLHO?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
     538        if( (isSSA?1.:0.) + (isL1L2?1.:0.) + (isMOLHO?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
    539539         iscoupling = true;
    540540        else
     
    553553                        finiteelement = P1Enum;
    554554                }
    555                 else if(isMLHO){
    556                         approximation = MLHOApproximationEnum;
     555                else if(isMOLHO){
     556                        approximation = MOLHOApproximationEnum;
    557557                        finiteelement = P1Enum;
    558558                }
     
    630630                         break;
    631631                case L1L2ApproximationEnum: numdofs = 2; break;
    632                 case MLHOApproximationEnum: numdofs = 4; break;
     632                case MOLHOApproximationEnum: numdofs = 4; break;
    633633                case HOApproximationEnum:
    634634                         switch(domaintype){
     
    695695        int    FrictionCoupling;
    696696        int*   finiteelement_list=NULL;
    697         bool   isSSA,isL1L2,isMLHO,isHO,isFS,iscoupling;
     697        bool   isSSA,isL1L2,isMOLHO,isHO,isFS,iscoupling;
    698698        bool   control_analysis;
    699699        bool   dakota_analysis;
     
    703703        iomodel->FindConstant(&isSSA,"md.flowequation.isSSA");
    704704        iomodel->FindConstant(&isL1L2,"md.flowequation.isL1L2");
    705         iomodel->FindConstant(&isMLHO,"md.flowequation.isMLHO");
     705        iomodel->FindConstant(&isMOLHO,"md.flowequation.isMOLHO");
    706706        iomodel->FindConstant(&isHO,"md.flowequation.isHO");
    707707        iomodel->FindConstant(&isFS,"md.flowequation.isFS");
     
    713713
    714714        /*return if no processing required*/
    715         if(!isSSA && !isL1L2 && !isMLHO && !isHO && !isFS) return;
     715        if(!isSSA && !isL1L2 && !isMOLHO && !isHO && !isFS) return;
    716716
    717717        /*Fetch data needed and allocate vectors: */
     
    720720
    721721        /*Do we have coupling*/
    722         if( (isSSA?1.:0.) + (isL1L2?1.:0.) + (isMLHO?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
     722        if( (isSSA?1.:0.) + (isL1L2?1.:0.) + (isMOLHO?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
    723723         iscoupling = true;
    724724        else
     
    729729                if(isSSA)       iomodel->FindConstant(&finiteelement,"md.flowequation.fe_SSA");
    730730                else if(isL1L2) finiteelement = P1Enum;
    731                 else if(isMLHO) finiteelement = P1Enum;
     731                else if(isMOLHO) finiteelement = P1Enum;
    732732                else if(isHO)   iomodel->FindConstant(&finiteelement,"md.flowequation.fe_HO");
    733733                else if(isFS)   iomodel->FindConstant(&finiteelement,"md.flowequation.fe_FS");
     
    781781        iomodel->FetchDataToInput(inputs,elements,"md.initialization.vx",VxEnum,0.);
    782782        iomodel->FetchDataToInput(inputs,elements,"md.initialization.vy",VyEnum,0.);
    783         /*MLHO*/
    784         if(isMLHO){
     783        /*MOLHO*/
     784        if(isMOLHO){
    785785                iomodel->FetchDataToInput(inputs,elements,"md.initialization.vx",VxShearEnum,0.);
    786786                iomodel->FetchDataToInput(inputs,elements,"md.initialization.vy",VyShearEnum,0.);
    787                 /*3D MLHO also need to have VxBase and VyBase for reconstruting Vx and Vy*/
     787                /*3D MOLHO also need to have VxBase and VyBase for reconstruting Vx and Vy*/
    788788                if (iomodel->domaintype==Domain3DEnum) {
    789789                        iomodel->FetchDataToInput(inputs,elements,"md.initialization.vx",VxBaseEnum,0.);
     
    836836                                break;
    837837                        case SpatialLinearFloatingMeltRateEnum:
    838                                 iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_melting_rate",BasalforcingsDeepwaterMeltingRateEnum);
    839                                 iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_elevation",BasalforcingsDeepwaterElevationEnum);
    840                                 iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.upperwater_elevation",BasalforcingsUpperwaterElevationEnum);
     838                                iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_melting_rate",BasalforcingsSpatialDeepwaterMeltingRateEnum);
     839                                iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_elevation",BasalforcingsSpatialDeepwaterElevationEnum);
     840                                iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.upperwater_melting_rate",BasalforcingsSpatialUpperwaterMeltingRateEnum);
     841                                iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.upperwater_elevation",BasalforcingsSpatialUpperwaterElevationEnum);
     842                                if(isstochastic){
     843                                        iomodel->FetchDataToInput(inputs,elements,"md.stochasticforcing.default_id",StochasticForcingDefaultIdEnum);
     844                                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_melting_rate",BaselineBasalforcingsSpatialDeepwaterMeltingRateEnum);
     845                                }
    841846                                break;
    842847                        case BasalforcingsPicoEnum:
     
    985990        parameters->AddObject(iomodel->CopyConstantObject("md.flowequation.isSSA",FlowequationIsSSAEnum));
    986991        parameters->AddObject(iomodel->CopyConstantObject("md.flowequation.isL1L2",FlowequationIsL1L2Enum));
    987         parameters->AddObject(iomodel->CopyConstantObject("md.flowequation.isMLHO",FlowequationIsMLHOEnum));
     992        parameters->AddObject(iomodel->CopyConstantObject("md.flowequation.isMOLHO",FlowequationIsMOLHOEnum));
    988993        parameters->AddObject(iomodel->CopyConstantObject("md.flowequation.isHO",FlowequationIsHOEnum));
    989994        parameters->AddObject(iomodel->CopyConstantObject("md.flowequation.isFS",FlowequationIsFSEnum));
     
    10881093
    10891094        /*Intermediaries*/
    1090         bool isSSA,isL1L2,isMLHO,isHO,isFS;
     1095        bool isSSA,isL1L2,isMOLHO,isHO,isFS;
    10911096        bool conserve_loads = true;
    10921097        int  newton,domaintype,fe_FS;
     
    10951100        femmodel->parameters->FindParam(&isSSA,FlowequationIsSSAEnum);
    10961101        femmodel->parameters->FindParam(&isL1L2,FlowequationIsL1L2Enum);
    1097         femmodel->parameters->FindParam(&isMLHO,FlowequationIsMLHOEnum);
     1102        femmodel->parameters->FindParam(&isMOLHO,FlowequationIsMOLHOEnum);
    10981103        femmodel->parameters->FindParam(&isHO,FlowequationIsHOEnum);
    10991104        femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
     
    11021107        femmodel->parameters->FindParam(&newton,StressbalanceIsnewtonEnum);
    11031108
    1104         if(isFS && !(isSSA || isHO || isL1L2 || isMLHO)){
     1109        if(isFS && !(isSSA || isHO || isL1L2 || isMOLHO)){
    11051110                femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
    11061111
     
    11241129                 solutionsequence_nonlinear(femmodel,conserve_loads);
    11251130        }
    1126         else if(!isFS && (isSSA || isHO || isL1L2 || isMLHO)){
     1131        else if(!isFS && (isSSA || isHO || isL1L2 || isMOLHO)){
    11271132                femmodel->SetCurrentConfiguration(StressbalanceAnalysisEnum);
    11281133                if(newton>0)
     
    11381143                }
    11391144        }
    1140         else if ((isSSA || isL1L2 || isMLHO || isHO) && isFS){
     1145        else if ((isSSA || isL1L2 || isMOLHO || isHO) && isFS){
    11411146                if(VerboseSolution()) _printf0_("   computing coupling between lower order models and FS\n");
    11421147                solutionsequence_FScoupling_nonlinear(femmodel,conserve_loads);
     
    11901195                case L1L2ApproximationEnum:
    11911196                        return CreateKMatrixL1L2(element);
    1192                 case MLHOApproximationEnum:
    1193                         return CreateKMatrixMLHO(element);
     1197                case MOLHOApproximationEnum:
     1198                        return CreateKMatrixMOLHO(element);
    11941199                case HOApproximationEnum:
    11951200                        return CreateKMatrixHO(element);
     
    12191224                case L1L2ApproximationEnum:
    12201225                        return CreatePVectorL1L2(element);
    1221                 case MLHOApproximationEnum:
    1222                         return CreatePVectorMLHO(element);
     1226                case MOLHOApproximationEnum:
     1227                        return CreatePVectorMOLHO(element);
    12231228                case HOApproximationEnum:
    12241229                        return CreatePVectorHO(element);
     
    12481253                        GetSolutionFromInputsHoriz(solution,element);
    12491254                        return;
    1250                 case MLHOApproximationEnum:
    1251                         GetSolutionFromInputsMLHO(solution,element);
     1255                case MOLHOApproximationEnum:
     1256                        GetSolutionFromInputsMOLHO(solution,element);
    12521257                        return;
    12531258                case SSAHOApproximationEnum: case HOFSApproximationEnum: case SSAFSApproximationEnum:
     
    13301335                        InputUpdateFromSolutionL1L2(solution,element);
    13311336                        return;
    1332                 case MLHOApproximationEnum:
    1333                         InputUpdateFromSolutionMLHO(solution,element);
     1337                case MOLHOApproximationEnum:
     1338                        InputUpdateFromSolutionMOLHO(solution,element);
    13341339                        return;
    13351340                case SSAHOApproximationEnum:
     
    27552760}/*}}}*/
    27562761
    2757 /*MLHO*/
    2758 ElementMatrix* StressbalanceAnalysis::CreateKMatrixMLHO(Element* element){/*{{{*/
     2762/*MOLHO*/
     2763ElementMatrix* StressbalanceAnalysis::CreateKMatrixMOLHO(Element* element){/*{{{*/
    27592764
    27602765        /* Check if ice in element */
     
    27792784
    27802785        /*compute all stiffness matrices for this element*/
    2781         ElementMatrix* Ke1=CreateKMatrixMLHOViscous(basalelement);
    2782         ElementMatrix* Ke2=CreateKMatrixMLHOFriction(basalelement);
     2786        ElementMatrix* Ke1=CreateKMatrixMOLHOViscous(basalelement);
     2787        ElementMatrix* Ke2=CreateKMatrixMOLHOFriction(basalelement);
    27832788        ElementMatrix* Ke =new ElementMatrix(Ke1,Ke2);
    27842789
     
    27892794        return Ke;
    27902795}/*}}}*/
    2791 ElementMatrix* StressbalanceAnalysis::CreateKMatrixMLHOFriction(Element* element){/*{{{*/
     2796ElementMatrix* StressbalanceAnalysis::CreateKMatrixMOLHOFriction(Element* element){/*{{{*/
    27922797
    27932798        if(element->IsAllFloating()) return NULL;
     
    28162821
    28172822        /*Initialize Element matrix and vectors*/
    2818         ElementMatrix* Ke = element->NewElementMatrix(MLHOApproximationEnum);
     2823        ElementMatrix* Ke = element->NewElementMatrix(MOLHOApproximationEnum);
    28192824        IssmDouble*    basis  = xNew<IssmDouble>(numnodes);
    28202825
     
    28712876        return Ke;
    28722877}/*}}}*/
    2873 ElementMatrix* StressbalanceAnalysis::CreateKMatrixMLHOViscous(Element* element){/*{{{*/
     2878ElementMatrix* StressbalanceAnalysis::CreateKMatrixMOLHOViscous(Element* element){/*{{{*/
    28742879
    28752880        /* Check if ice in element */
     
    28862891
    28872892        /*Initialize Element matrix and vectors*/
    2888         ElementMatrix* Ke     = element->NewElementMatrix(MLHOApproximationEnum);
     2893        ElementMatrix* Ke     = element->NewElementMatrix(MOLHOApproximationEnum);
    28892894        IssmDouble*    dbasis = xNew<IssmDouble>(2*numnodes); // like SSA
    28902895        IssmDouble*    basis  = xNew<IssmDouble>(numnodes); // like SSA
     
    29102915                thickness_input->GetInputValue(&thickness, gauss);
    29112916                n_input->GetInputValue(&n,gauss);
    2912                 element->material->ViscosityMLHO(&viscosity[0],dim,xyz_list,gauss,vxbase_input,vybase_input,vxshear_input,vyshear_input,thickness_input,n_input);
     2917                element->material->ViscosityMOLHO(&viscosity[0],dim,xyz_list,gauss,vxbase_input,vybase_input,vxshear_input,vyshear_input,thickness_input,n_input);
    29132918
    29142919                for(int i=0;i<numnodes;i++){//shape functions on tria element
     
    29762981
    29772982        /*Transform Coordinate System*/
    2978         //basalelement->TransformStiffnessMatrixCoord(Ke,XYMLHOEnum);
     2983        //basalelement->TransformStiffnessMatrixCoord(Ke,XYMOLHOEnum);
    29792984
    29802985        /*Clean up and return*/
     
    29852990        return Ke;
    29862991}/*}}}*/
    2987 ElementVector* StressbalanceAnalysis::CreatePVectorMLHO(Element* element){/*{{{*/
     2992ElementVector* StressbalanceAnalysis::CreatePVectorMOLHO(Element* element){/*{{{*/
    29882993
    29892994        /* Check if ice in element */
     
    30083013
    30093014        /*compute all load vectors for this element*/
    3010         ElementVector* pe1=CreatePVectorMLHODrivingStress(basalelement);
    3011         ElementVector* pe2=CreatePVectorMLHOFront(basalelement);
     3015        ElementVector* pe1=CreatePVectorMOLHODrivingStress(basalelement);
     3016        ElementVector* pe2=CreatePVectorMOLHOFront(basalelement);
    30123017        ElementVector* pe =new ElementVector(pe1,pe2);
    30133018
     
    30183023        return pe;
    30193024}/*}}}*/
    3020 ElementVector* StressbalanceAnalysis::CreatePVectorMLHODrivingStress(Element* element){/*{{{*/
     3025ElementVector* StressbalanceAnalysis::CreatePVectorMOLHODrivingStress(Element* element){/*{{{*/
    30213026
    30223027        /*Intermediaries */
     
    30283033
    30293034        /*Initialize Element vector and vectors*/
    3030         ElementVector* pe    = element->NewElementVector(MLHOApproximationEnum);
     3035        ElementVector* pe    = element->NewElementVector(MOLHOApproximationEnum);
    30313036        IssmDouble*    basis = xNew<IssmDouble>(numnodes);
    30323037
     
    30573062
    30583063        /*Transform coordinate system*/
    3059         //element->TransformLoadVectorCoord(pe,XYMLHOEnum);
     3064        //element->TransformLoadVectorCoord(pe,XYMOLHOEnum);
    30603065
    30613066        /*Clean up and return*/
     
    30653070        return pe;
    30663071}/*}}}*/
    3067 ElementVector* StressbalanceAnalysis::CreatePVectorMLHOFront(Element* element){/*{{{*/
     3072ElementVector* StressbalanceAnalysis::CreatePVectorMOLHOFront(Element* element){/*{{{*/
    30683073
    30693074        /*If no front, return NULL*/
     
    30813086
    30823087        /*Initialize Element vector and other vectors*/
    3083         ElementVector* pe    = element->NewElementVector(MLHOApproximationEnum);
     3088        ElementVector* pe    = element->NewElementVector(MOLHOApproximationEnum);
    30843089        IssmDouble*    basis = xNew<IssmDouble>(numnodes);
    30853090
     
    31303135
    31313136        /*Transform coordinate system*/
    3132         //element->TransformLoadVectorCoord(pe,XYMLHOEnum);
     3137        //element->TransformLoadVectorCoord(pe,XYMOLHOEnum);
    31333138
    31343139        /*Clean up and return*/
     
    31393144        return pe;
    31403145}/*}}}*/
    3141 void           StressbalanceAnalysis::InputUpdateFromSolutionMLHO(IssmDouble* solution,Element* element){/*{{{*/
     3146void           StressbalanceAnalysis::InputUpdateFromSolutionMOLHO(IssmDouble* solution,Element* element){/*{{{*/
    31423147
    31433148        int         i,dim,domaintype;
     
    31923197
    31933198        /*Fetch dof list and allocate solution vectors*/
    3194         basalelement->GetDofListLocal(&doflist,MLHOApproximationEnum,GsetEnum);
     3199        basalelement->GetDofListLocal(&doflist,MOLHOApproximationEnum,GsetEnum);
    31953200        IssmDouble* values    = xNew<IssmDouble>(numdof);
    31963201        IssmDouble* vbx       = xNew<IssmDouble>(numnodes);
     
    32153220
    32163221   /*Ok, we have vx and vy in values, fill in vx and vy arrays: */
    3217    for(i=0;i<numnodes;i++){ //numnodes of the 2D mesh in which the MLHO is written
     3222   for(i=0;i<numnodes;i++){ //numnodes of the 2D mesh in which the MOLHO is written
    32183223      vbx[i] =values[i*4+0]; //base vx
    32193224      vshx[i]=values[i*4+1]; //shear vx
     
    32523257   switch(domaintype){
    32533258      case Domain2DhorizontalEnum:
    3254                         for(i=0;i<numnodes;i++){ //numnodes of the 2D mesh in which the MLHO is written
     3259                        for(i=0;i<numnodes;i++){ //numnodes of the 2D mesh in which the MOLHO is written
    32553260                                vx[i]=vbx[i]+vshx[i]*(n[i]+1)/(n[i]+2);
    32563261                                vy[i]=vby[i]+vshy[i]*(n[i]+1)/(n[i]+2);
     
    32643269                   basalelement->GetInputListOnNodes(&H[0],ThicknessEnum,0.);
    32653270                   basalelement->GetInputListOnNodes(&s[0],SurfaceEnum,0.);
    3266                         element->Recover3DMLHOInput(VxEnum, numnodes, vbx, vshx, n, H, s);
    3267                         element->Recover3DMLHOInput(VyEnum, numnodes, vby, vshy, n, H, s);
     3271                        element->Recover3DMOLHOInput(VxEnum, numnodes, vbx, vshx, n, H, s);
     3272                        element->Recover3DMOLHOInput(VyEnum, numnodes, vby, vshy, n, H, s);
    32683273                        break;
    32693274                default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
     
    32893294        if(basalelement->IsSpawnedElement()){basalelement->DeleteMaterials(); delete basalelement;};
    32903295}/*}}}*/
    3291 void           StressbalanceAnalysis::GetSolutionFromInputsMLHO(Vector<IssmDouble>* solution,Element* element){/*{{{*/
     3296void           StressbalanceAnalysis::GetSolutionFromInputsMOLHO(Vector<IssmDouble>* solution,Element* element){/*{{{*/
    32923297
    32933298        IssmDouble   vbx,vby,vshx,vshy;
     
    33083313        int numdof   = numnodes*dofpernode;
    33093314        element->GetInputValue(&approximation,ApproximationEnum);
    3310         if(approximation!=MLHOApproximationEnum) _error_("mesh "<<EnumToStringx(approximation)<<" not supported here");
     3315        if(approximation!=MOLHOApproximationEnum) _error_("mesh "<<EnumToStringx(approximation)<<" not supported here");
    33113316
    33123317        /*Fetch dof list and allocate solution vector*/
  • issm/trunk/src/c/analyses/StressbalanceAnalysis.h

    r26744 r27035  
    5757                ElementVector* CreatePVectorL1L2DrivingStress(Element* element);
    5858                void           InputUpdateFromSolutionL1L2(IssmDouble* solution,Element* element);
    59                 /*MLHO*/
    60                 ElementMatrix* CreateKMatrixMLHO(Element* element);
    61                 ElementMatrix* CreateKMatrixMLHOFriction(Element* element);
    62                 ElementMatrix* CreateKMatrixMLHOViscous(Element* element);
    63                 ElementVector* CreatePVectorMLHO(Element* element);
    64                 ElementVector* CreatePVectorMLHOFront(Element* element);
    65                 ElementVector* CreatePVectorMLHODrivingStress(Element* element);
    66                 void           InputUpdateFromSolutionMLHO(IssmDouble* solution,Element* element);
    67                 void           GetSolutionFromInputsMLHO(Vector<IssmDouble>* solution,Element* element);
     59                /*MOLHO*/
     60                ElementMatrix* CreateKMatrixMOLHO(Element* element);
     61                ElementMatrix* CreateKMatrixMOLHOFriction(Element* element);
     62                ElementMatrix* CreateKMatrixMOLHOViscous(Element* element);
     63                ElementVector* CreatePVectorMOLHO(Element* element);
     64                ElementVector* CreatePVectorMOLHOFront(Element* element);
     65                ElementVector* CreatePVectorMOLHODrivingStress(Element* element);
     66                void           InputUpdateFromSolutionMOLHO(IssmDouble* solution,Element* element);
     67                void           GetSolutionFromInputsMOLHO(Vector<IssmDouble>* solution,Element* element);
    6868                /*HO*/
    6969                ElementMatrix* CreateJacobianMatrixHO(Element* element);
  • issm/trunk/src/c/analyses/StressbalanceSIAAnalysis.cpp

    r26744 r27035  
    1010
    1111        /*Intermediaries*/
    12         bool       isSIA,isSSA,isL1L2,isMLHO,isHO,isFS,iscoupling;
     12        bool       isSIA,isSSA,isL1L2,isMOLHO,isHO,isFS,iscoupling;
    1313
    1414        /*Fetch parameters: */
     
    1616        iomodel->FindConstant(&isSSA,"md.flowequation.isSSA");
    1717        iomodel->FindConstant(&isL1L2,"md.flowequation.isL1L2");
    18         iomodel->FindConstant(&isMLHO,"md.flowequation.isMLHO");
     18        iomodel->FindConstant(&isMOLHO,"md.flowequation.isMOLHO");
    1919        iomodel->FindConstant(&isHO,"md.flowequation.isHO");
    2020        iomodel->FindConstant(&isFS,"md.flowequation.isFS");
     
    2424
    2525        /*Do we have coupling*/
    26         if((isSIA?1.:0.) + (isSSA?1.:0.) + (isL1L2?1.:0.) + (isMLHO?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
     26        if((isSIA?1.:0.) + (isSSA?1.:0.) + (isL1L2?1.:0.) + (isMOLHO?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
    2727         iscoupling = true;
    2828        else
  • issm/trunk/src/c/analyses/StressbalanceVerticalAnalysis.cpp

    r26744 r27035  
    1212
    1313        /*Intermediary*/
    14         bool        isSIA,isSSA,isL1L2,isMLHO,isHO,isFS,iscoupling;
     14        bool        isSIA,isSSA,isL1L2,isMOLHO,isHO,isFS,iscoupling;
    1515        int         Mz,Nz;
    1616        IssmDouble *spcvz = NULL;
     
    2323        iomodel->FindConstant(&isSSA,"md.flowequation.isSSA");
    2424        iomodel->FindConstant(&isL1L2,"md.flowequation.isL1L2");
    25         iomodel->FindConstant(&isMLHO,"md.flowequation.isMLHO");
     25        iomodel->FindConstant(&isMOLHO,"md.flowequation.isMOLHO");
    2626        iomodel->FindConstant(&isHO,"md.flowequation.isHO");
    2727        iomodel->FindConstant(&isFS,"md.flowequation.isFS");
    2828
    2929        /*Do we have coupling*/
    30         if((isSIA?1.:0.) + (isSSA?1.:0.) + (isL1L2?1.:0.) + (isMLHO?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
     30        if((isSIA?1.:0.) + (isSSA?1.:0.) + (isL1L2?1.:0.) + (isMOLHO?1.:0.) + (isHO?1.:0.) + (isFS?1.:0.) >1.)
    3131         iscoupling = true;
    3232        else
     
    139139                        break;
    140140                case SpatialLinearFloatingMeltRateEnum:
    141                         iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_melting_rate",BasalforcingsDeepwaterMeltingRateEnum);
    142                         iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_elevation",BasalforcingsDeepwaterElevationEnum);
    143                         iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.upperwater_elevation",BasalforcingsUpperwaterElevationEnum);
     141                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_melting_rate",BasalforcingsSpatialDeepwaterMeltingRateEnum);
     142                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_elevation",BasalforcingsSpatialDeepwaterElevationEnum);
     143                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.upperwater_melting_rate",BasalforcingsSpatialUpperwaterMeltingRateEnum);
     144                        iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.upperwater_elevation",BasalforcingsSpatialUpperwaterElevationEnum);
     145                        if(isstochastic){
     146            iomodel->FetchDataToInput(inputs,elements,"md.stochasticforcing.default_id",StochasticForcingDefaultIdEnum);
     147            iomodel->FetchDataToInput(inputs,elements,"md.basalforcings.deepwater_melting_rate",BaselineBasalforcingsSpatialDeepwaterMeltingRateEnum);
     148         }
    144149                        break;
    145150                case BasalforcingsPicoEnum:
  • issm/trunk/src/c/classes/Cfdragcoeffabsgrad.cpp

    r26744 r27035  
    3030        this->name = NULL;
    3131        this->weights_enum = UNDEF;
    32         this->misfit=0;
    3332        this->timepassedflag = false;
    3433}
     
    4342        this->weights_enum=in_weights_enum;
    4443        this->timepassedflag=in_timepassedflag;
    45 
    46         this->misfit=0;
    4744}
    4845/*}}}*/
    4946Cfdragcoeffabsgrad::~Cfdragcoeffabsgrad(){/*{{{*/
    5047        if(this->name)xDelete(this->name);
    51         this->misfit=0;
    5248}
    5349/*}}}*/
     
    5551Object* Cfdragcoeffabsgrad::copy() {/*{{{*/
    5652        Cfdragcoeffabsgrad* mf = new Cfdragcoeffabsgrad(this->name,this->definitionenum, this->weights_enum,this->timepassedflag);
    57         mf->misfit=this->misfit;
    5853        return (Object*) mf;
    5954}
     
    115110        int        domaintype,numcomponents;
    116111        IssmDouble Jelem=0.;
    117         IssmDouble misfit,Jdet;
     112        IssmDouble Jdet;
    118113        IssmDouble dp[2],weight;
    119114        IssmDouble* xyz_list = NULL;
  • issm/trunk/src/c/classes/Cfdragcoeffabsgrad.h

    r26744 r27035  
    1111
    1212IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,int output_enum);
    13 void  GetVectorFromInputsx( IssmDouble** pvector, int* pvector_size, FemModel* femmodel,int name);
    1413
    1514class Cfdragcoeffabsgrad: public Object, public Definition{
     
    2120                int         weights_enum;
    2221                bool                    timepassedflag;
    23 
    24                 IssmDouble  misfit; //value carried over in time.
    2522
    2623                /*Cfdragcoeffabsgrad constructors, destructors :*/
  • issm/trunk/src/c/classes/Cflevelsetmisfit.cpp

    r26744 r27035  
    3232        this->observation_enum = UNDEF;
    3333        this->weights_enum = UNDEF;
    34         this->misfit=0;
    3534        this->datatime=0.;
    3635        this->timepassedflag = false;
     
    4948        this->datatime=in_datatime;
    5049        this->timepassedflag=in_timepassedflag;
    51 
    52         this->misfit=0;
    5350}
    5451/*}}}*/
    5552Cflevelsetmisfit::~Cflevelsetmisfit(){/*{{{*/
    5653        if(this->name)xDelete(this->name);
    57         this->misfit=0;
    5854}
    5955/*}}}*/
     
    6157Object* Cflevelsetmisfit::copy() {/*{{{*/
    6258        Cflevelsetmisfit* mf = new Cflevelsetmisfit(this->name,this->definitionenum, this->model_enum,this->observation_enum,this->weights_enum,this->datatime,this->timepassedflag);
    63         mf->misfit=this->misfit;
    6459        return (Object*) mf;
    6560}
     
    9590        marshallhandle->call(this->datatime);
    9691        marshallhandle->call(this->timepassedflag);
    97         marshallhandle->call(this->misfit);
    9892}
    9993/*}}}*/
  • issm/trunk/src/c/classes/Cflevelsetmisfit.h

    r26744 r27035  
    1111
    1212IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,int output_enum);
    13 void  GetVectorFromInputsx( IssmDouble** pvector, int* pvector_size, FemModel* femmodel,int name);
    1413
    1514class Cflevelsetmisfit: public Object, public Definition{
     
    2423                IssmDouble      datatime;
    2524                bool                    timepassedflag;
    26 
    27                 IssmDouble  misfit; //value carried over in time.
    2825
    2926                /*Cflevelsetmisfit constructors, destructors :*/
  • issm/trunk/src/c/classes/Cfsurfacelogvel.cpp

    r26744 r27035  
    2929        this->definitionenum = -1;
    3030        this->name = NULL;
    31         this->misfit=0;
    3231        this->datatime=0.;
    3332        this->timepassedflag = false;
     
    4544        this->timepassedflag=in_timepassedflag;
    4645
    47         this->misfit=0;
    4846}
    4947/*}}}*/
    5048Cfsurfacelogvel::~Cfsurfacelogvel(){/*{{{*/
    5149        if(this->name)xDelete(this->name);
    52         this->misfit=0;
    5350}
    5451/*}}}*/
     
    5653Object* Cfsurfacelogvel::copy() {/*{{{*/
    5754        Cfsurfacelogvel* mf = new Cfsurfacelogvel(this->name,this->definitionenum,this->datatime,this->timepassedflag);
    58         mf->misfit=this->misfit;
    5955        return (Object*) mf;
    6056}
     
    7571/*}}}*/
    7672void Cfsurfacelogvel::Marshall(MarshallHandle* marshallhandle){/*{{{*/
    77         _error_("not implemented yet!");
     73        int object_enum=CfsurfacelogvelEnum;
     74        marshallhandle->call(object_enum);
     75
     76        marshallhandle->call(this->definitionenum);
     77        marshallhandle->call(this->name);
     78        marshallhandle->call(this->datatime);
     79        marshallhandle->call(this->timepassedflag);
    7880}
    7981/*}}}*/
     
    100102        femmodel->parameters->FindParam(&time,TimeEnum);
    101103
    102         IssmDouble J=0.;
    103         IssmDouble J_sum=0.;
    104         if(this->datatime<=time && !timepassedflag){
     104        if(this->datatime<=time && !this->timepassedflag){
     105
     106                IssmDouble J=0.;
     107                IssmDouble J_sum=0.;
     108
    105109                for(Object* & object : femmodel->elements->objects){
    106110                        Element* element=xDynamicCast<Element*>(object);
     
    113117
    114118                this->timepassedflag = true;
    115         }
    116         return J;
     119                return J_sum;
     120        }
     121        else{
     122                return 0.;
     123        }
    117124}/*}}}*/
    118125IssmDouble Cfsurfacelogvel::Cfsurfacelogvel_Calculation(Element* element, int definitionenum){/*{{{*/
  • issm/trunk/src/c/classes/Cfsurfacelogvel.h

    r26744 r27035  
    1111
    1212IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,int output_enum);
    13 void  GetVectorFromInputsx( IssmDouble** pvector, int* pvector_size, FemModel* femmodel,int name);
    1413
    1514class Cfsurfacelogvel: public Object, public Definition{
     
    2120                IssmDouble      datatime;
    2221                bool                    timepassedflag;
    23 
    24                 IssmDouble  misfit; //value carried over in time.
    2522
    2623                /*Cfsurfacelogvel constructors, destructors :*/
  • issm/trunk/src/c/classes/Cfsurfacesquare.cpp

    r26744 r27035  
    66/*{{{*/
    77#ifdef HAVE_CONFIG_H
    8    #include <config.h>
     8#include <config.h>
    99#else
    1010#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
     
    2727Cfsurfacesquare::Cfsurfacesquare(){/*{{{*/
    2828
    29         this->definitionenum = -1;
    30         this->name = NULL;
    31         this->model_enum = UNDEF;
     29        this->definitionenum   = -1;
     30        this->name             = NULL;
     31        this->model_enum       = UNDEF;
    3232        this->observation_enum = UNDEF;
    33         this->weights_enum = UNDEF;
    34         this->misfit=0;
    35         this->datatime=0.;
    36         this->timepassedflag = false;
     33        this->weights_enum     = UNDEF;
     34        this->datatime         = 0.;
     35        this->timepassedflag   = false;
    3736}
    3837/*}}}*/
     
    4948        this->datatime=in_datatime;
    5049        this->timepassedflag=in_timepassedflag;
    51 
    52         this->misfit=0;
    5350}
    5451/*}}}*/
    5552Cfsurfacesquare::~Cfsurfacesquare(){/*{{{*/
    5653        if(this->name)xDelete(this->name);
    57         this->misfit=0;
    58 }
    59 /*}}}*/
     54}
     55/*}}}*/
     56
    6057/*Object virtual function resolutoin: */
    6158Object* Cfsurfacesquare::copy() {/*{{{*/
    6259        Cfsurfacesquare* mf = new Cfsurfacesquare(this->name,this->definitionenum, this->model_enum,this->observation_enum,this->weights_enum,this->datatime,this->timepassedflag);
    63         mf->misfit=this->misfit;
    6460        return (Object*) mf;
    6561}
     
    9591        marshallhandle->call(this->datatime);
    9692        marshallhandle->call(this->timepassedflag);
    97         marshallhandle->call(this->misfit);
    9893}
    9994/*}}}*/
     
    10297}
    10398/*}}}*/
     99
    104100/*Definition virtual function resolutoin: */
    105101int Cfsurfacesquare::DefinitionEnum(){/*{{{*/
     
    115111/*}}}*/
    116112IssmDouble Cfsurfacesquare::Response(FemModel* femmodel){/*{{{*/
    117          /*diverse: */
    118          IssmDouble time;
    119 
    120          /*recover time parameters: */
    121          femmodel->parameters->FindParam(&time,TimeEnum);
    122 
    123          IssmDouble J=0.;
    124          IssmDouble J_sum=0.;
    125 
    126          if(datatime<=time && !timepassedflag){
    127                  for(Object* & object : femmodel->elements->objects){
    128                          Element* element=xDynamicCast<Element*>(object);
    129                          J+=this->Cfsurfacesquare_Calculation(element,model_enum,observation_enum,weights_enum);
    130                  }
    131 
    132                  ISSM_MPI_Allreduce ( (void*)&J,(void*)&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
    133                  ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
    134                  J=J_sum;
    135 
    136                  timepassedflag = true;
    137                  return J;
    138          }
    139          else return J;
    140  }
    141         /*}}}*/
     113
     114        /*recover time parameters: */
     115        IssmDouble time;
     116        femmodel->parameters->FindParam(&time,TimeEnum);
     117
     118        /*Do the calculation only if this is the first time we are passed datatime*/
     119        if(this->datatime<=time && !this->timepassedflag){
     120
     121                IssmDouble J=0.;
     122                IssmDouble J_sum=0.;
     123
     124                for(Object* & object : femmodel->elements->objects){
     125                        Element* element=xDynamicCast<Element*>(object);
     126                        J+=this->Cfsurfacesquare_Calculation(element,model_enum,observation_enum,weights_enum);
     127                }
     128
     129                ISSM_MPI_Allreduce ( (void*)&J,(void*)&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
     130                ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
     131
     132                this->timepassedflag = true;
     133                return J_sum;
     134        }
     135        else{
     136                return 0.;
     137        }
     138}
     139/*}}}*/
    142140IssmDouble Cfsurfacesquare::Cfsurfacesquare_Calculation(Element* element, int model_enum, int observation_enum, int weights_enum){/*{{{*/
    143141
  • issm/trunk/src/c/classes/Cfsurfacesquare.h

    r26744 r27035  
    1111
    1212IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,int output_enum);
    13 void  GetVectorFromInputsx( IssmDouble** pvector, int* pvector_size, FemModel* femmodel,int name);
    1413
    1514class Cfsurfacesquare: public Object, public Definition{
     
    2524                IssmDouble      datatime;
    2625                bool                    timepassedflag;
    27 
    28                 IssmDouble  misfit; //value carried over in time.
    2926
    3027                /*Cfsurfacesquare constructors, destructors :*/
  • issm/trunk/src/c/classes/Elements/Element.cpp

    r26744 r27035  
    6969
    7070   /*Get Basin ID and Basin coefficients*/
    71    if(enum_type==SMBautoregressionEnum)                   this->GetInputValue(&basinid,SmbBasinsIdEnum);
    72    if(enum_type==FrontalForcingsRignotAutoregressionEnum) this->GetInputValue(&basinid,FrontalForcingsBasinIdEnum);
     71   if(enum_type==SMBautoregressionEnum)                               this->GetInputValue(&basinid,SmbBasinsIdEnum);
     72   if(enum_type==FrontalForcingsRignotAutoregressionEnum)             this->GetInputValue(&basinid,FrontalForcingsBasinIdEnum);
     73   if(enum_type==BasalforcingsDeepwaterMeltingRateAutoregressionEnum) this->GetInputValue(&basinid,BasalforcingsLinearBasinIdEnum);
    7374   for(int i=0;i<arorder;i++) phi_basin[i] = phi[basinid*arorder+i];
    7475   beta0_basin   = beta0[basinid];
     
    9293      xDelete<IssmDouble>(oldvarspin);
    9394   }
    94    if(enum_type==SMBautoregressionEnum)                   this->inputs->SetArrayInput(SmbValuesAutoregressionEnum,this->lid,varspin,numvertices*arorder);
    95    if(enum_type==FrontalForcingsRignotAutoregressionEnum) this->inputs->SetArrayInput(ThermalforcingValuesAutoregressionEnum,this->lid,varspin,numvertices*arorder);
     95   if(enum_type==SMBautoregressionEnum)                               this->inputs->SetArrayInput(SmbValuesAutoregressionEnum,this->lid,varspin,numvertices*arorder);
     96   if(enum_type==FrontalForcingsRignotAutoregressionEnum)             this->inputs->SetArrayInput(ThermalforcingValuesAutoregressionEnum,this->lid,varspin,numvertices*arorder);
     97   if(enum_type==BasalforcingsDeepwaterMeltingRateAutoregressionEnum) this->inputs->SetArrayInput(BasalforcingsDeepwaterMeltingRateValuesAutoregressionEnum,this->lid,varspin,numvertices*arorder);
    9698
    9799   /*Cleanup and return*/
     
    123125         outenum_type   = FrontalForcingsThermalForcingEnum;
    124126         break;
     127                case(BasalforcingsDeepwaterMeltingRateAutoregressionEnum):
     128         arenum_type    = BasalforcingsDeepwaterMeltingRateValuesAutoregressionEnum;
     129         basinenum_type = BasalforcingsLinearBasinIdEnum;
     130         noiseenum_type = BasalforcingsDeepwaterMeltingRateNoiseEnum;
     131         outenum_type   = BasalforcingsSpatialDeepwaterMeltingRateEnum;
     132         break;
    125133   }
    126134
     
    172180   xDelete<IssmDouble>(varlist);
    173181   xDelete<IssmDouble>(valuesautoregression);
     182}/*}}}*/
     183void       Element::BasinLinearFloatingiceMeltingRate(IssmDouble* deepwaterel,IssmDouble* upperwatermelt,IssmDouble* upperwaterel,IssmDouble* perturbation){/*{{{*/
     184
     185        const int NUM_VERTICES = this->GetNumberOfVertices();
     186
     187        int basinid;
     188   IssmDouble alpha;
     189   IssmDouble base[MAXVERTICES];
     190   IssmDouble values[MAXVERTICES];
     191   IssmDouble deepwatermelt[MAXVERTICES];
     192
     193        /*Get element-specific values*/
     194        this->GetInputValue(&basinid,BasalforcingsLinearBasinIdEnum);
     195        this->GetInputListOnVertices(&base[0],BaseEnum);
     196   this->GetInputListOnVertices(&deepwatermelt[0],BasalforcingsSpatialDeepwaterMeltingRateEnum);
     197
     198        /*Compute melt rate at vertices according to basin-specific values of input arguments*/
     199   for(int i=0;i<NUM_VERTICES;i++){
     200                if(base[i]>=upperwaterel[basinid]){
     201         values[i]=upperwatermelt[basinid];
     202      }
     203      else if (base[i]<deepwaterel[basinid]){
     204         values[i]=deepwatermelt[i];
     205      }
     206      else{
     207         alpha = (base[i]-upperwaterel[basinid])/(deepwaterel[basinid]-upperwaterel[basinid]);
     208         values[i]=deepwatermelt[i]*alpha+(1.-alpha)*upperwatermelt[basinid];
     209      }
     210   }
     211
     212   this->AddInput(BasalforcingsFloatingiceMeltingRateEnum,&values[0],P1Enum);
     213}/*}}}*/
     214void       Element::CalvingFromRate(){/*{{{*/
     215
     216        /*We are provided a calving rate, figure out the x/y components*/
     217        int         dim,domaintype;
     218        IssmDouble  vx,vy,vel,dphidx,dphidy,dphi,c;
     219        IssmDouble  calvingratex[MAXVERTICES];
     220        IssmDouble  calvingratey[MAXVERTICES];
     221
     222        /*Get problem dimension and whether there is moving front or not*/
     223        this->FindParam(&domaintype,DomainTypeEnum);
     224
     225        switch(domaintype){
     226                case Domain2DverticalEnum:   dim = 1; break;
     227                case Domain2DhorizontalEnum: dim = 2; break;
     228                case Domain3DEnum:           dim = 2; break;
     229                default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
     230        }
     231        if(dim==1) _error_("not implemented in 1D...");
     232
     233        Input *calvingrate_input = this->GetInput(CalvingCalvingrateEnum);     _assert_(calvingrate_input);
     234        Input *vx_input          = this->GetInput(VxEnum);  _assert_(vx_input);
     235        Input *vy_input          = this->GetInput(VyEnum); _assert_(vy_input);
     236        Input *lsf_slopex_input  = this->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
     237        Input *lsf_slopey_input  = this->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
     238
     239        /*Allocate arrays*/
     240        const int NUM_VERTICES = this->GetNumberOfVertices();
     241
     242        /* Start looping on the number of vertices: */
     243        Gauss* gauss=this->NewGauss();
     244        for (int iv=0;iv<NUM_VERTICES;iv++){
     245                gauss->GaussVertex(iv);
     246
     247      calvingrate_input->GetInputValue(&c,gauss);
     248                vx_input->GetInputValue(&vx,gauss);
     249                vy_input->GetInputValue(&vy,gauss);
     250                lsf_slopex_input->GetInputValue(&dphidx,gauss);
     251                lsf_slopey_input->GetInputValue(&dphidy,gauss);
     252
     253                vel=sqrt(vx*vx + vy*vy) + 1e-14;
     254                dphi=sqrt(dphidx*dphidx+dphidy*dphidy)+ 1e-14;
     255
     256                if(false){
     257                        /*Velocity direction*/
     258                        calvingratex[iv] = c*vx/vel;
     259         calvingratey[iv] = c*vy/vel;
     260                }
     261                else{
     262                        /*Lelvelset gradient (perpendicular to ice front)*/
     263         calvingratex[iv] = c*dphidx/dphi;
     264         calvingratey[iv] = c*dphidy/dphi;
     265                }
     266        }
     267
     268
     269        /*Add to inputs*/
     270        this->AddInput(CalvingratexEnum,&calvingratex[0],P1DGEnum);
     271        this->AddInput(CalvingrateyEnum,&calvingratey[0],P1DGEnum);
     272        //this->AddInput(CalvingCalvingrateEnum,&calvingrate[0],P1DGEnum); /*Do not change calving rate, that's our input!*/
     273
     274        /*Clean up and return*/
     275        delete gauss;
     276}/*}}}*/
     277void       Element::CalvingSetZeroRate(){/*{{{*/
     278
     279        /*Set calving rate as 0, this is probably because we are  dealing with discrete calving laws*/
     280        IssmDouble  calvingratex[MAXVERTICES] = {0.};
     281        IssmDouble  calvingratey[MAXVERTICES] = {0.};
     282        IssmDouble  calvingrate[MAXVERTICES]  = {0.};
     283        this->AddInput(CalvingratexEnum,&calvingratex[0],P1DGEnum);
     284        this->AddInput(CalvingrateyEnum,&calvingratey[0],P1DGEnum);
     285        this->AddInput(CalvingCalvingrateEnum,&calvingrate[0],P1DGEnum);
    174286}/*}}}*/
    175287void       Element::ComputeLambdaS(){/*{{{*/
     
    9291041}
    9301042/*}}}*/
    931 void       Element::dViscositydBMLHO(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vxbase_input,Input* vybase_input, Input* vxshear_input ,Input* vyshear_input,Input* thickness_input,Input* n_input, IssmDouble zeta){/*{{{*/
     1043void       Element::dViscositydBMOLHO(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vxbase_input,Input* vybase_input, Input* vxshear_input ,Input* vyshear_input,Input* thickness_input,Input* n_input, IssmDouble zeta){/*{{{*/
    9321044
    9331045        /*Intermediaries*/
     
    9391051
    9401052        /* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy */
    941    this->StrainRateMLHO(&epsilon[0],xyz_list,gauss,
     1053   this->StrainRateMOLHO(&epsilon[0],xyz_list,gauss,
    9421054                                vxbase_input,vybase_input,vxshear_input,vyshear_input,thickness_input,n_input,zeta);
    9431055   eps_eff=sqrt(epsilon[0]*epsilon[0] + epsilon[1]*epsilon[1] + epsilon[2]*epsilon[2]
     
    21582270        return shelf;
    21592271}/*}}}*/
     2272bool       Element::IsAllGrounded(){/*{{{*/
     2273
     2274        Input* input=this->GetInput(MaskOceanLevelsetEnum); _assert_(input);
     2275        if(input->GetInputMin() < 0.){
     2276                return false;
     2277        }
     2278        else{
     2279                return true;
     2280        }
     2281}/*}}}*/
    21602282bool       Element::IsGrounded(){/*{{{*/
    21612283
     
    22572379
    22582380}/*}}}*/
     2381void       Element::LapseRateBasinSMB(int numelevbins, IssmDouble* lapserates, IssmDouble* elevbins,IssmDouble* refelevation){/*{{{*/
     2382
     2383        /*Variable declaration*/
     2384   const int numvertices = this->GetNumberOfVertices();
     2385   bool isadjustsmb = false;
     2386        int basinid,bb1,bb2;
     2387   IssmDouble ela,refelevation_b;
     2388   IssmDouble* surfacelist  = xNew<IssmDouble>(numvertices);
     2389   IssmDouble* smblist      = xNew<IssmDouble>(numvertices);
     2390   /* numelevbins values of lapse rates */
     2391        IssmDouble* lapserates_b = xNew<IssmDouble>(numelevbins);
     2392   /* (numelevbins-1) limits between elevation bins (be cautious with indexing) */
     2393        IssmDouble* elevbins_b   = xNew<IssmDouble>(numelevbins-1);
     2394
     2395   /*Retrieve SMB values non-adjusted for SMB lapse rate*/
     2396   this->GetInputListOnVertices(smblist,SmbMassBalanceEnum);
     2397        /*Get surface elevation on vertices*/
     2398        this->GetInputListOnVertices(surfacelist,SurfaceEnum);
     2399   /*Get basin-specific parameters of the element*/
     2400   this->GetInputValue(&basinid,SmbBasinsIdEnum);
     2401   refelevation_b = refelevation[basinid];
     2402        for(int ii=0;ii<(numelevbins-1);ii++) elevbins_b[ii] = elevbins[basinid*(numelevbins-1)+ii];
     2403        for(int ii=0;ii<numelevbins;ii++){
     2404                lapserates_b[ii] = lapserates[basinid*numelevbins+ii];
     2405                if(lapserates_b[ii]!=0) isadjustsmb=true;
     2406        }
     2407        /*Adjust SMB if any lapse rate value is non-zero*/
     2408        if(isadjustsmb){
     2409       
     2410           for(int v=0;v<numvertices;v++){
     2411              /*Find elevation bin of Reference elevation and of Vertex*/
     2412                        for(int ii=0;ii<(numelevbins-1);ii++){
     2413                                if(surfacelist[v]<=elevbins_b[ii]) bb1 = ii;   
     2414                                if(refelevation_b<=elevbins_b[ii]) bb2 = ii;
     2415                        }
     2416                        /*Check for elevations above highest bin limit */
     2417                        if(surfacelist[v]>elevbins_b[numelevbins-1-1]) bb1 = numelevbins-1;
     2418                        if(refelevation_b>elevbins_b[numelevbins-1-1]) bb2 = numelevbins-1;
     2419                        /*Vertex and Reference elevation in same elevation bin*/
     2420                        if(bb1==bb2){
     2421                                smblist[v] = smblist[v]+(surfacelist[v]-refelevation_b)*lapserates_b[bb2];
     2422                        }
     2423                        /*Vertex in lower elevation bin than Reference elevation*/
     2424                        if(bb1<bb2){
     2425                                smblist[v] = smblist[v]+(elevbins_b[bb2-1]-refelevation_b)*lapserates_b[bb2];
     2426                                for(int ii=bb2-1;ii>bb1;ii--) smblist[v] = smblist[v]+(elevbins_b[ii-1]-elevbins_b[ii])*lapserates_b[ii];
     2427                                smblist[v] = smblist[v]+(surfacelist[v]-elevbins_b[bb1])*lapserates_b[bb1];
     2428                        }
     2429                        /*Vertex in higher elevation bin than Reference elevation*/
     2430                        if(bb1>bb2){
     2431                                smblist[v] = smblist[v]+(elevbins_b[bb2]-refelevation_b)*lapserates_b[bb2];
     2432                                for(int ii=bb2+1;ii<bb1;ii++) smblist[v] = smblist[v]+(elevbins_b[ii]-elevbins_b[ii-1])*lapserates_b[ii];
     2433                                smblist[v] = smblist[v]+(surfacelist[v]-elevbins_b[bb1-1])*lapserates_b[bb1];
     2434                        }
     2435                }
     2436        }
     2437
     2438   /*Add input to element*/
     2439   this->AddInput(SmbMassBalanceEnum,smblist,P1Enum);
     2440
     2441   /*Cleanup*/
     2442   xDelete<IssmDouble>(lapserates_b);
     2443   xDelete<IssmDouble>(elevbins_b);
     2444   xDelete<IssmDouble>(surfacelist);
     2445   xDelete<IssmDouble>(smblist);
     2446}/*}}}*/
    22592447void       Element::LinearFloatingiceMeltingRate(){/*{{{*/
    22602448
     
    22642452        IssmDouble base[MAXVERTICES];
    22652453        IssmDouble values[MAXVERTICES];
    2266         IssmDouble perturbation[MAXVERTICES];
    22672454        IssmDouble time;
    22682455
     
    22752462
    22762463        this->GetInputListOnVertices(&base[0],BaseEnum);
    2277    this->GetInputListOnVertices(&perturbation[0],BasalforcingsPerturbationMeltingRateEnum);
    22782464        for(int i=0;i<NUM_VERTICES;i++){
    22792465                if(base[i]>=upperwaterel){
     
    22872473                        values[i]=deepwatermelt*alpha+(1.-alpha)*upperwatermelt;
    22882474                }
    2289 
    2290       values[i]+=perturbation[i];
    22912475        }
    22922476
     
    22982482        const int NUM_VERTICES = this->GetNumberOfVertices();
    22992483
     2484        IssmDouble alpha;
    23002485        IssmDouble deepwatermelt[MAXVERTICES];
    2301         IssmDouble deepwaterel[MAXVERTICES];;
     2486        IssmDouble deepwaterel[MAXVERTICES];
     2487        IssmDouble upperwatermelt[MAXVERTICES];
    23022488        IssmDouble upperwaterel[MAXVERTICES];
     2489        IssmDouble perturbation[MAXVERTICES];
    23032490        IssmDouble base[MAXVERTICES];
    23042491        IssmDouble values[MAXVERTICES];
    23052492
    23062493        this->GetInputListOnVertices(&base[0],BaseEnum);
    2307         this->GetInputListOnVertices(&deepwatermelt[0],BasalforcingsDeepwaterMeltingRateEnum);
    2308         this->GetInputListOnVertices(&deepwaterel[0],BasalforcingsDeepwaterElevationEnum);
    2309         this->GetInputListOnVertices(&upperwaterel[0],BasalforcingsUpperwaterElevationEnum);
     2494        this->GetInputListOnVertices(&deepwatermelt[0],BasalforcingsSpatialDeepwaterMeltingRateEnum);
     2495        this->GetInputListOnVertices(&deepwaterel[0],BasalforcingsSpatialDeepwaterElevationEnum);
     2496        this->GetInputListOnVertices(&upperwatermelt[0],BasalforcingsSpatialUpperwaterMeltingRateEnum);
     2497        this->GetInputListOnVertices(&upperwaterel[0],BasalforcingsSpatialUpperwaterElevationEnum);
     2498   this->GetInputListOnVertices(&perturbation[0],BasalforcingsPerturbationMeltingRateEnum);
    23102499
    23112500        for(int i=0;i<NUM_VERTICES;i++){
    2312                 if(base[i]>upperwaterel[i])      values[i]=0;
    2313                 else if (base[i]<deepwaterel[i]) values[i]=deepwatermelt[i];
    2314                 else values[i]=deepwatermelt[i]*(base[i]-upperwaterel[i])/(deepwaterel[i]-upperwaterel[i]);
     2501                if(base[i]>=upperwaterel[i]){
     2502                        values[i]=upperwatermelt[i];
     2503                }
     2504                else if (base[i]<deepwaterel[i]){
     2505                        values[i]=deepwatermelt[i];
     2506                }
     2507                else{
     2508                        alpha = (base[i]-upperwaterel[i])/(deepwaterel[i]-upperwaterel[i]);
     2509                        values[i]=deepwatermelt[i]*alpha+(1.-alpha)*upperwatermelt[i];
     2510                }
     2511                values[i] += perturbation[i];
    23152512        }
    23162513
     
    30503247                                                case P1xP3Enum:
    30513248                                                case P1xP4Enum:
     3249                                                case P1DGEnum:
    30523250                                                        temp_input->element_values[3] = yearlytemperatures[3];
    30533251                                                        temp_input->element_values[4] = yearlytemperatures[4];
     
    30743272                                                        case P1xP3Enum:
    30753273                                                        case P1xP4Enum:
     3274                                                        case P1DGEnum:
    30763275                                                                ThermalToEnthalpy(&enth_input->element_values[3],yearlytemperatures[3],0.,0.);
    30773276                                                                ThermalToEnthalpy(&enth_input->element_values[4],yearlytemperatures[4],0.,0.);
     
    33553554                                                                                                                  this->CalvingCrevasseDepth();
    33563555                                                                                                                  break;
     3556                                                                                                          case CalvingParameterizationEnum:
     3557                                                                                                                  this->CalvingRateParameterization();
     3558                                                                                                                  break;
     3559                                                                                                          case CalvingTestEnum:
     3560                                                                                                                  this->CalvingRateTest();
     3561                                                                                                                  break;
    33573562                                                                                                          default:
    33583563                                                                                                                  _error_("Calving law "<<EnumToStringx(calvinglaw)<<" not supported yet");
     
    33643569                case StrainRateperpendicularEnum: this->StrainRateperpendicular(); break;
    33653570                case SurfaceCrevasseEnum: this->CalvingCrevasseDepth(); break;
    3366                 case SigmaVMEnum: this->CalvingRateVonmises(); break;
     3571                case SigmaVMEnum: this->ComputeSigmaVM(); break;
    33673572                case PartitioningEnum: this->inputs->SetInput(PartitioningEnum,this->lid,IssmComm::GetRank()); break;
    33683573        }
     
    44144619
    44154620}/*}}}*/
    4416 void       Element::StrainRateMLHO(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vxbase_input,Input* vybase_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input,IssmDouble zeta){/*{{{*/
    4417         /*Compute the 2d Blatter/MLHO Strain Rate (5 components) for a given vertical coordinate (zeta):
     4621void       Element::StrainRateMOLHO(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vxbase_input,Input* vybase_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input,IssmDouble zeta){/*{{{*/
     4622        /*Compute the 2d Blatter/MOLHO Strain Rate (5 components) for a given vertical coordinate (zeta):
    44184623         *
    44194624         * epsilon=[exx eyy exy exz eyz]
  • issm/trunk/src/c/classes/Elements/Element.h

    r26744 r27035  
    7070                void                                     AutoregressionInit(int numbasins,int arorder,int nspin,IssmDouble starttime,IssmDouble tstep_ar,IssmDouble tinit_ar,IssmDouble* beta0,IssmDouble* beta1,IssmDouble* phi,int enum_type);
    7171      void               Autoregression(bool isstepforar,int arorder,IssmDouble telapsed_ar,IssmDouble* beta0,IssmDouble* beta1,IssmDouble* phi,bool isfieldstochastic,int enum_type);
     72                void               BasinLinearFloatingiceMeltingRate(IssmDouble* deepwaterel,IssmDouble* upperwatermelt,IssmDouble* upperwaterel,IssmDouble* perturbation);
     73                void               CalvingSetZeroRate(void);
     74                void               CalvingFromRate(void);
    7275                void               ComputeLambdaS(void);
    7376                void               ComputeNewDamage();
     
    8386                void               dViscositydBHO(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
    8487                void               dViscositydBSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
    85                 void               dViscositydBMLHO(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vxbase_input,Input* vybase_input, Input* vxshear_input ,Input* vyshear_input,Input* thickness_input,Input* n_input, IssmDouble zeta);
     88                void               dViscositydBMOLHO(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vxbase_input,Input* vybase_input, Input* vxshear_input ,Input* vyshear_input,Input* thickness_input,Input* n_input, IssmDouble zeta);
    8689                void               dViscositydDSSA(IssmDouble* pdmudB,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
    8790                void               Echo();
     
    144147
    145148                bool               IsAllFloating();
     149                bool               IsAllGrounded();
    146150                bool               IsGrounded();
    147151                bool               IsOnBase();
     
    153157                bool               IsLandInElement();
    154158                void               Ismip6FloatingiceMeltingRate();
     159                void               LapseRateBasinSMB(int numelevbins, IssmDouble* lapserates, IssmDouble* elevbins,IssmDouble* refelevation);
    155160                void               LinearFloatingiceMeltingRate();
    156161                void               SpatialLinearFloatingiceMeltingRate();
     
    185190                void               StrainRateHO(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
    186191                void               StrainRateHO2dvertical(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
    187                 void               StrainRateMLHO(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input,IssmDouble zeta);
     192                void               StrainRateMOLHO(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input,IssmDouble zeta);
    188193                void               StrainRateSSA(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
    189194                void               StrainRateSSA1d(IssmDouble* epsilon,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input);
     
    227232                virtual void       AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part)=0;
    228233                virtual void             BasalNodeIndices(int* pnumindices,int** pindices,int finiteelement){_error_("not implemented yet");};
     234                virtual void       CalvingRateParameterization(void){_error_("not implemented yet");};
    229235                virtual void       CalvingRateVonmises(void){_error_("not implemented yet");};
     236                virtual void       CalvingRateTest(void){_error_("not implemented yet");};
    230237                virtual void       CalvingCrevasseDepth(void){_error_("not implemented yet");};
    231238                virtual void        CalvingRateLevermann(void)=0;
     
    236243                virtual void       ComputeDeviatoricStressTensor(void)=0;
    237244                virtual void       ComputeSigmaNN(void)=0;
     245                virtual void       ComputeSigmaVM(void){_error_("not implemented yet");};
    238246                virtual void       ComputeStressTensor(void)=0;
    239247                virtual void       ComputeEsaStrainAndVorticity(void)=0;
     
    343351                virtual void       PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding)=0;
    344352                virtual int        PressureInterpolation()=0;
    345       virtual void       Recover3DMLHOInput(int targetVel_enum, int numnodes, IssmDouble* vb,  IssmDouble* vsh, IssmDouble* n, IssmDouble* H, IssmDouble* s){_error_("not implemented yet");};
     353      virtual void       Recover3DMOLHOInput(int targetVel_enum, int numnodes, IssmDouble* vb,  IssmDouble* vsh, IssmDouble* n, IssmDouble* H, IssmDouble* s){_error_("not implemented yet");};
    346354                virtual void       ReduceMatrices(ElementMatrix* Ke,ElementVector* pe)=0;
    347355                virtual void       ResetFSBasalBoundaryCondition()=0;
     
    395403
    396404                virtual void       SealevelchangeGeometrySubElementKernel(SealevelGeometry* slgeom)=0;
    397                 virtual void       SealevelchangeMomentOfInertiaCentroid(IssmDouble* dI_list, GrdLoads* loads, SealevelGeometry* slgeom)=0;
    398405                virtual void       SealevelchangeShift(GrdLoads* loads, IssmDouble offset, SealevelGeometry* slgeom)=0;
    399406                virtual void       SealevelchangeGeometryInitial(IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae)=0;
     
    404411                virtual void       SealevelchangeOceanAverage(GrdLoads* loads, Vector<IssmDouble>* oceanareas, Vector<IssmDouble>* subelementoceanareas, IssmDouble* sealevelpercpu, SealevelGeometry* slgeom)=0;
    405412                virtual void       SealevelchangeDeformationConvolution(IssmDouble* sealevelpercpu, GrdLoads* loads, IssmDouble* rotationvector,SealevelGeometry* slgeom)=0;
    406                 virtual void       SealevelchangeMomentOfInertiaSubElement(IssmDouble* dI_list, GrdLoads* loads, SealevelGeometry* slgeom)=0;
    407                 virtual void       SealevelchangeUpdateViscousFields()=0;
     413                virtual void       SealevelchangeUpdateViscousFields(IssmDouble lincoeff, int newindex, int offset)=0;
    408414                #endif
    409415
  • issm/trunk/src/c/classes/Elements/Penta.cpp

    r26744 r27035  
    271271
    272272        if(!this->IsOnBase()) return;
    273 
    274         IssmDouble  xyz_list[NUMVERTICES][3];
    275         IssmDouble  epsilon[3]; /* epsilon=[exx,eyy,exy];*/
    276         IssmDouble  calvingratex[NUMVERTICES];
    277         IssmDouble  calvingratey[NUMVERTICES];
     273        this->ComputeSigmaVM();
     274
    278275        IssmDouble  calvingrate[NUMVERTICES];
    279         IssmDouble  lambda1,lambda2,ex,ey,vx,vy,vel;
    280         IssmDouble  B,sigma_max,sigma_max_floating,sigma_max_grounded,n;
    281         IssmDouble  epse_2,groundedice,bed,sealevel;
    282         IssmDouble  sigma_vm[NUMVERTICES];
    283 
    284         /* Get node coordinates and dof list: */
    285         ::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
     276        IssmDouble  vx,vy;
     277        IssmDouble  sigma_vm,sigma_max,sigma_max_floating,sigma_max_grounded;
     278        IssmDouble  groundedice,bed,sealevel;
    286279
    287280        /*Depth average B for stress calculation*/
    288         this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
    289281        this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
    290282        this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
     
    295287        Input* gr_input = this->GetInput(MaskOceanLevelsetEnum); _assert_(gr_input);
    296288        Input* bs_input = this->GetInput(BaseEnum);                    _assert_(bs_input);
    297         Input* B_input  = this->GetInput(MaterialsRheologyBbarEnum);   _assert_(B_input);
    298         Input* n_input  = this->GetInput(MaterialsRheologyNEnum);   _assert_(n_input);
    299289        Input* smax_fl_input = this->GetInput(CalvingStressThresholdFloatingiceEnum); _assert_(smax_fl_input);
    300290        Input* smax_gr_input = this->GetInput(CalvingStressThresholdGroundediceEnum); _assert_(smax_gr_input);
    301291        Input* sl_input  = this->GetInput(SealevelEnum); _assert_(sl_input);
     292        Input* sigma_vm_input = this->GetInput(SigmaVMEnum); _assert_(sigma_vm_input);
    302293
    303294        /* Start looping on the number of vertices: */
     
    307298
    308299                /*Get velocity components and thickness*/
    309                 B_input->GetInputValue(&B,&gauss);
    310                 n_input->GetInputValue(&n,&gauss);
    311300                vx_input->GetInputValue(&vx,&gauss);
    312301                vy_input->GetInputValue(&vy,&gauss);
     302                sigma_vm_input->GetInputValue(&sigma_vm,&gauss);
    313303                gr_input->GetInputValue(&groundedice,&gauss);
    314304                bs_input->GetInputValue(&bed,&gauss);
    315305                smax_fl_input->GetInputValue(&sigma_max_floating,&gauss);
    316306                smax_gr_input->GetInputValue(&sigma_max_grounded,&gauss);
    317                 vel=sqrt(vx*vx+vy*vy)+1.e-14;
    318307                sl_input->GetInputValue(&sealevel,&gauss);
    319 
    320                 /*Compute strain rate and viscosity: */
    321                 this->StrainRateSSA(&epsilon[0],&xyz_list[0][0],&gauss,vx_input,vy_input);
    322 
    323                 /*Get Eigen values*/
    324                 Matrix2x2Eigen(&lambda1,&lambda2,&ex,&ey,epsilon[0],epsilon[2],epsilon[1]);
    325                 _assert_(!xIsNan<IssmDouble>(lambda1));
    326                 _assert_(!xIsNan<IssmDouble>(lambda2));
    327 
    328                 /*Process Eigen values (only account for extension)*/
    329                 lambda1 = max(lambda1,0.);
    330                 lambda2 = max(lambda2,0.);
    331 
    332                 /*Calculate sigma_vm*/
    333                 epse_2    = 1./2. *(lambda1*lambda1 + lambda2*lambda2);
    334                 sigma_vm[iv] = sqrt(3.) * B * pow(epse_2,1./(2.*n));
    335308
    336309                /*Tensile stress threshold*/
     
    342315                /*Assign values*/
    343316                if(bed>sealevel){
    344                         calvingratex[iv]=0.;
    345                         calvingratey[iv]=0.;
     317                        calvingrate[iv] = 0.;
    346318                }
    347319                else{
    348                         calvingratex[iv]=vx*sigma_vm[iv]/sigma_max;
    349                         calvingratey[iv]=vy*sigma_vm[iv]/sigma_max;
    350                 }
    351                 calvingrate[iv] =sqrt(calvingratex[iv]*calvingratex[iv] + calvingratey[iv]*calvingratey[iv]);
     320                        calvingrate[iv] = sqrt(vx*vx+vy*vy)*sigma_vm/sigma_max;
     321                }
    352322        }
    353323
    354324        /*Add input*/
    355         this->AddBasalInput(CalvingratexEnum,&calvingratex[0],P1DGEnum);
    356         this->AddBasalInput(CalvingrateyEnum,&calvingratey[0],P1DGEnum);
    357325        this->AddBasalInput(CalvingCalvingrateEnum,&calvingrate[0],P1DGEnum);
    358         this->AddBasalInput(SigmaVMEnum,&sigma_vm[0],P1DGEnum);
    359 
     326        this->CalvingFromRate();
     327
     328        /*Extrude*/
     329        this->InputExtrude(CalvingCalvingrateEnum,-1);
    360330        this->InputExtrude(CalvingratexEnum,-1);
    361331        this->InputExtrude(CalvingrateyEnum,-1);
    362         this->InputExtrude(CalvingCalvingrateEnum,-1);
    363         this->InputExtrude(SigmaVMEnum,-1);
    364332}
    365333/*}}}*/
     
    847815        this->AddInput(StressTensoryzEnum,&sigma_yz[0],P1DGEnum);
    848816        this->AddInput(StressTensorzzEnum,&sigma_zz[0],P1DGEnum);
     817}
     818/*}}}*/
     819void       Penta::ComputeSigmaVM(){/*{{{*/
     820
     821        if(!this->IsOnBase()) return;
     822
     823        IssmDouble  xyz_list[NUMVERTICES][3];
     824        IssmDouble  epsilon[3]; /* epsilon=[exx,eyy,exy];*/
     825        IssmDouble  lambda1,lambda2,ex,ey,vx,vy,vel;
     826        IssmDouble  B,n;
     827        IssmDouble  sigma_vm[NUMVERTICES];
     828
     829        /* Get node coordinates and dof list: */
     830        ::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
     831
     832        /*Depth average B for stress calculation*/
     833        this->InputDepthAverageAtBase(MaterialsRheologyBEnum,MaterialsRheologyBbarEnum);
     834        this->InputDepthAverageAtBase(VxEnum,VxAverageEnum);
     835        this->InputDepthAverageAtBase(VyEnum,VyAverageEnum);
     836
     837        /*Retrieve all inputs and parameters we will need*/
     838        Input* vx_input = this->GetInput(VxAverageEnum); _assert_(vx_input);
     839        Input* vy_input = this->GetInput(VyAverageEnum); _assert_(vy_input);
     840        Input* B_input  = this->GetInput(MaterialsRheologyBbarEnum);   _assert_(B_input);
     841        Input* n_input  = this->GetInput(MaterialsRheologyNEnum);   _assert_(n_input);
     842
     843        /* Start looping on the number of vertices: */
     844        GaussPenta gauss;
     845        for(int iv=0;iv<3;iv++){
     846                gauss.GaussVertex(iv);
     847
     848                /*Get velocity components and thickness*/
     849                B_input->GetInputValue(&B,&gauss);
     850                n_input->GetInputValue(&n,&gauss);
     851                vx_input->GetInputValue(&vx,&gauss);
     852                vy_input->GetInputValue(&vy,&gauss);
     853                vel=sqrt(vx*vx+vy*vy)+1.e-14;
     854
     855                /*Compute strain rate and viscosity: */
     856                this->StrainRateSSA(&epsilon[0],&xyz_list[0][0],&gauss,vx_input,vy_input);
     857
     858                /*Get Eigen values*/
     859                Matrix2x2Eigen(&lambda1,&lambda2,&ex,&ey,epsilon[0],epsilon[2],epsilon[1]);
     860                _assert_(!xIsNan<IssmDouble>(lambda1));
     861                _assert_(!xIsNan<IssmDouble>(lambda2));
     862
     863                /*Process Eigen values (only account for extension)*/
     864                lambda1 = max(lambda1,0.);
     865                lambda2 = max(lambda2,0.);
     866
     867                /*Calculate sigma_vm*/
     868                IssmDouble epse_2    = 1./2. *(lambda1*lambda1 + lambda2*lambda2);
     869                sigma_vm[iv] = sqrt(3.) * B * pow(epse_2,1./(2.*n));
     870        }
     871
     872        /*Add input*/
     873        this->AddBasalInput(SigmaVMEnum,&sigma_vm[0],P1DGEnum);
     874        this->InputExtrude(SigmaVMEnum,-1);
    849875}
    850876/*}}}*/
     
    28402866}
    28412867/*}}}*/
    2842 void       Penta::MovingFrontalVelocity(void){/*{{{*/
     2868void          Penta::MovingFrontalVelocity(void){/*{{{*/
     2869
    28432870        if(!this->IsOnBase()) return;
    2844         int  dim, domaintype, calvinglaw, i;
     2871        int        domaintype, calvinglaw, i;
    28452872        IssmDouble v[3],w[3],c[3],m[3],dlsf[3];
    28462873        IssmDouble norm_dlsf, norm_calving, calvingrate, meltingrate, groundedice;
    28472874        IssmDouble migrationmax, calvinghaf, heaviside, haf_eps;
    2848         IssmDouble  xyz_list[NUMVERTICES][3];
    2849         IssmDouble  movingfrontvx[NUMVERTICES];
    2850         IssmDouble  movingfrontvy[NUMVERTICES];
    2851         IssmDouble  vel;
     2875        IssmDouble xyz_list[NUMVERTICES][3];
     2876        IssmDouble movingfrontvx[NUMVERTICES];
     2877        IssmDouble movingfrontvy[NUMVERTICES];
     2878        IssmDouble vel;
     2879        int        dim=2;
    28522880
    28532881        /* Get node coordinates and dof list: */
    28542882        ::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
    2855 
    2856         Input* vx_input           = NULL;
    2857         Input* vy_input           = NULL;
    28582883        Input* calvingratex_input = NULL;
    28592884        Input* calvingratey_input = NULL;
    2860         Input* lsf_slopex_input   = NULL;
    2861         Input* lsf_slopey_input   = NULL;
    28622885        Input* calvingrate_input  = NULL;
    28632886        Input* meltingrate_input  = NULL;
    2864         Input* gr_input           = NULL;
     2887
     2888        /*Load levelset function gradients*/
     2889        Input *lsf_slopex_input = this->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
     2890        Input *lsf_slopey_input = this->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
     2891        Input *vx_input         = this->GetInput(VxAverageEnum);              _assert_(vx_input);
     2892        Input *vy_input         = this->GetInput(VyAverageEnum);              _assert_(vy_input);
     2893        Input *gr_input         = this->GetInput(MaskOceanLevelsetEnum);      _assert_(gr_input);
    28652894
    28662895        /*Get problem dimension and whether there is moving front or not*/
    2867         this->FindParam(&domaintype,DomainTypeEnum);
    28682896        this->FindParam(&calvinglaw,CalvingLawEnum);
    2869 
    2870         switch(domaintype){
    2871                 case Domain2DverticalEnum:   dim = 1; break;
    2872                 case Domain2DhorizontalEnum: dim = 2; break;
    2873                 case Domain3DEnum:           dim = 2; break;
    2874                 default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
    2875         }
    2876         /*Load velocities*/
    2877         switch(domaintype){
    2878                 case Domain2DverticalEnum:
    2879                         vx_input=this->GetInput(VxEnum); _assert_(vx_input);
    2880                         break;
    2881                 case Domain2DhorizontalEnum:
    2882                         vx_input=this->GetInput(VxEnum); _assert_(vx_input);
    2883                         vy_input=this->GetInput(VyEnum); _assert_(vy_input);
    2884                         gr_input=this->GetInput(MaskOceanLevelsetEnum); _assert_(gr_input);
    2885                         break;
    2886                 case Domain3DEnum:
    2887                         vx_input=this->GetInput(VxAverageEnum); _assert_(vx_input);
    2888                         vy_input=this->GetInput(VyAverageEnum); _assert_(vy_input);
    2889                         gr_input=this->GetInput(MaskOceanLevelsetEnum); _assert_(gr_input);
    2890                         break;
    2891                 default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
    2892         }
    2893 
    28942897        switch(calvinglaw){
    28952898                case DefaultCalvingEnum:
    28962899                case CalvingVonmisesEnum:
    2897                         lsf_slopex_input  = this->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
    2898                         if(dim==2) lsf_slopey_input  = this->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
    2899                         calvingrate_input = this->GetInput(CalvingCalvingrateEnum);     _assert_(calvingrate_input);
    2900                         meltingrate_input = this->GetInput(CalvingMeltingrateEnum);     _assert_(meltingrate_input);
    2901                         break;
    29022900                case CalvingLevermannEnum:
    2903                         switch(domaintype){
    2904                                 case Domain2DverticalEnum:
    2905                                         calvingratex_input=this->GetInput(CalvingratexEnum); _assert_(calvingratex_input);
    2906                                         break;
    2907                                 case Domain2DhorizontalEnum:
    2908                                         calvingratex_input=this->GetInput(CalvingratexEnum); _assert_(calvingratex_input);
    2909                                         calvingratey_input=this->GetInput(CalvingrateyEnum); _assert_(calvingratey_input);
    2910                                         break;
    2911                                 case Domain3DEnum:
    2912                                         calvingratex_input=this->GetInput(CalvingratexAverageEnum); _assert_(calvingratex_input);
    2913                                         calvingratey_input=this->GetInput(CalvingrateyAverageEnum); _assert_(calvingratey_input);
    2914                                         break;
    2915                                 default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
    2916                         }
     2901                        calvingratex_input=this->GetInput(CalvingratexEnum); _assert_(calvingratex_input);
     2902                        calvingratey_input=this->GetInput(CalvingrateyEnum); _assert_(calvingratey_input);
    29172903                        meltingrate_input = this->GetInput(CalvingMeltingrateEnum);     _assert_(meltingrate_input);
    29182904                        break;
    29192905                case CalvingMinthicknessEnum:
    2920                         lsf_slopex_input  = this->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
    2921                         if(dim==2) lsf_slopey_input  = this->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
    2922                         meltingrate_input = this->GetInput(CalvingMeltingrateEnum);     _assert_(meltingrate_input);
    2923                         break;
    29242906                case CalvingHabEnum:
    2925                         lsf_slopex_input  = this->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
    2926                         if(dim==2) lsf_slopey_input  = this->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
    2927                         meltingrate_input = this->GetInput(CalvingMeltingrateEnum);     _assert_(meltingrate_input);
    2928                         break;
    29292907                case CalvingCrevasseDepthEnum:
    2930                         lsf_slopex_input  = this->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
    2931                         if(dim==2) lsf_slopey_input  = this->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
    29322908                        meltingrate_input = this->GetInput(CalvingMeltingrateEnum);     _assert_(meltingrate_input);
    29332909                        break;
    29342910                case CalvingDev2Enum:
    29352911                        this->FindParam(&calvinghaf,CalvingHeightAboveFloatationEnum);
    2936                         lsf_slopex_input  = this->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
    2937                         if(dim==2) lsf_slopey_input  = this->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
    29382912                        calvingrate_input = this->GetInput(CalvingCalvingrateEnum);     _assert_(calvingrate_input);
    29392913                        meltingrate_input = this->GetInput(CalvingMeltingrateEnum);     _assert_(meltingrate_input);
     
    29522926                vy_input->GetInputValue(&v[1],&gauss);
    29532927                gr_input->GetInputValue(&groundedice,&gauss);
     2928      lsf_slopex_input->GetInputValue(&dlsf[0],&gauss);
     2929      lsf_slopey_input->GetInputValue(&dlsf[1],&gauss);
     2930      norm_dlsf=sqrt(dlsf[0]*dlsf[0] + dlsf[1]*dlsf[1]);
    29542931
    29552932                /*Get calving speed*/
     
    29572934                        case DefaultCalvingEnum:
    29582935                        case CalvingVonmisesEnum:
    2959                                 lsf_slopex_input->GetInputValue(&dlsf[0],&gauss);
    2960                                 if(dim==2) lsf_slopey_input->GetInputValue(&dlsf[1],&gauss);
    2961                                 calvingrate_input->GetInputValue(&calvingrate,&gauss);
    2962                                 meltingrate_input->GetInputValue(&meltingrate,&gauss);
    2963 
    2964                                 if(groundedice<0) meltingrate = 0.;
    2965 
    2966                                 norm_dlsf=0.;
    2967                                 for(i=0;i<dim;i++) norm_dlsf+=pow(dlsf[i],2);
    2968                                 norm_dlsf=sqrt(norm_dlsf);
    2969 
    2970                                 if(norm_dlsf>1.e-10)
    2971                                  for(i=0;i<dim;i++){
    2972                                          c[i]=calvingrate*dlsf[i]/norm_dlsf; m[i]=meltingrate*dlsf[i]/norm_dlsf;
    2973                                  }
    2974                                 else
    2975                                  for(i=0;i<dim;i++){
    2976                                          c[i]=0.; m[i]=0.;
    2977                                  }
    2978                                 break;
    2979 
    29802936                        case CalvingLevermannEnum:
    29812937                                calvingratex_input->GetInputValue(&c[0],&gauss);
    2982                                 if(dim==2) calvingratey_input->GetInputValue(&c[1],&gauss);
     2938                                calvingratey_input->GetInputValue(&c[1],&gauss);
    29832939                                meltingrate_input->GetInputValue(&meltingrate,&gauss);
    2984                                 norm_calving=0.;
    2985                                 for(i=0;i<dim;i++) norm_calving+=pow(c[i],2);
    2986                                 norm_calving=sqrt(norm_calving)+1.e-14;
    2987                                 for(i=0;i<dim;i++) m[i]=meltingrate*c[i]/norm_calving;
     2940                                if(groundedice<0) meltingrate = 0.;
     2941                                m[0]=meltingrate*dlsf[0]/norm_dlsf;
     2942                                m[1]=meltingrate*dlsf[1]/norm_dlsf;
    29882943                                break;
    29892944
    29902945                        case CalvingMinthicknessEnum:
    2991                                 lsf_slopex_input->GetInputValue(&dlsf[0],&gauss);
    2992                                 if(dim==2) lsf_slopey_input->GetInputValue(&dlsf[1],&gauss);
     2946                        case CalvingHabEnum:
     2947                        case CalvingCrevasseDepthEnum:
    29932948                                meltingrate_input->GetInputValue(&meltingrate,&gauss);
    2994 
    2995                                 norm_dlsf=0.;
    2996                                 for(i=0;i<dim;i++) norm_dlsf+=pow(dlsf[i],2);
    2997                                 norm_dlsf=sqrt(norm_dlsf);
     2949                                if(groundedice<0) meltingrate = 0.;
    29982950
    29992951                                if(norm_dlsf>1.e-10)
     
    30092961                                break;
    30102962
    3011                         case CalvingHabEnum:
    3012                                 lsf_slopex_input->GetInputValue(&dlsf[0],&gauss);
    3013                                 if(dim==2) lsf_slopey_input->GetInputValue(&dlsf[1],&gauss);
    3014                                 meltingrate_input->GetInputValue(&meltingrate,&gauss);
    3015 
    3016                                 norm_dlsf=0.;
    3017                                 for(i=0;i<dim;i++) norm_dlsf+=pow(dlsf[i],2);
    3018                                 norm_dlsf=sqrt(norm_dlsf);
    3019 
    3020                                 if(norm_dlsf>1.e-10)
    3021                                  for(i=0;i<dim;i++){
    3022                                          c[i]=0.;
    3023                                          m[i]=meltingrate*dlsf[i]/norm_dlsf;
    3024                                  }
    3025                                 else
    3026                                  for(i=0;i<dim;i++){
    3027                                          c[i]=0.;
    3028                                          m[i]=0.;
    3029                                  }
    3030                                 break;
    3031 
    3032                         case CalvingCrevasseDepthEnum:
    3033                                 lsf_slopex_input->GetInputValue(&dlsf[0],&gauss);
    3034                                 if(dim==2) lsf_slopey_input->GetInputValue(&dlsf[1],&gauss);
    3035                                 meltingrate_input->GetInputValue(&meltingrate,&gauss);
    3036 
    3037                                 if(groundedice<0) meltingrate = 0.;
    3038 
    3039                                 norm_dlsf=0.;
    3040                                 for(i=0;i<dim;i++) norm_dlsf+=pow(dlsf[i],2);
    3041                                 norm_dlsf=sqrt(norm_dlsf);
    3042 
    3043                                 if(norm_dlsf>1.e-10)
    3044                                  for(i=0;i<dim;i++){
    3045                                          c[i]=0.;
    3046                                          m[i]=meltingrate*dlsf[i]/norm_dlsf;
    3047                                  }
    3048                                 else
    3049                                  for(i=0;i<dim;i++){
    3050                                          c[i]=0.;
    3051                                          m[i]=0.;
    3052                                  }
    3053                                 break;
    3054 
    30552963                        case CalvingDev2Enum:
    30562964                                  {
    3057                                         lsf_slopex_input->GetInputValue(&dlsf[0],&gauss);
    3058                                         if(dim==2) lsf_slopey_input->GetInputValue(&dlsf[1],&gauss);
    30592965                                        calvingrate_input->GetInputValue(&calvingrate,&gauss);
    30602966                                        meltingrate_input->GetInputValue(&meltingrate,&gauss);
     
    30812987                                        }
    30822988
    3083                                         norm_dlsf=0.;
    3084                                         for(i=0;i<dim;i++) norm_dlsf+=pow(dlsf[i],2);
    3085                                         norm_dlsf=sqrt(norm_dlsf);
    3086 
    30872989                                        if(norm_dlsf>1.e-10)
    30882990                                         for(i=0;i<dim;i++){
     
    31113013        this->AddInput(MovingFrontalVxEnum,&movingfrontvx[0],P1DGEnum);
    31123014        this->AddInput(MovingFrontalVyEnum,&movingfrontvy[0],P1DGEnum);
    3113 
    31143015        this->InputExtrude(MovingFrontalVxEnum,-1);
    31153016        this->InputExtrude(MovingFrontalVyEnum,-1);
     
    32963197        norm=sqrt(normal[0]*normal[0]+normal[1]*normal[1]+normal[2]*normal[2]);
    32973198
    3298         for(int i=0;i<3;i++) normal[i]=normal[i]/norm;
     3199        for(int i=0;i<3;i++) normal[i]=normal[i]/(norm+1e-10);
    32993200}
    33003201/*}}}*/
     
    33813282}
    33823283/*}}}*/
    3383 void       Penta::Recover3DMLHOInput(int targetVel_enum, int numnodes, IssmDouble* vb,  IssmDouble* vsh, IssmDouble* n, IssmDouble* H, IssmDouble* s){/*{{{*/
     3284void       Penta::Recover3DMOLHOInput(int targetVel_enum, int numnodes, IssmDouble* vb,  IssmDouble* vsh, IssmDouble* n, IssmDouble* H, IssmDouble* s){/*{{{*/
    33843285   /* Recover the velocity acording to v=vb+(1-\zeta^{n+1})vsh, where \zeta=(s-z)/H
    33853286    * The variables vb, vsh, n, H and s are all from the 2D horizontal mesh(Tria), with "numnodes" DOFs
  • issm/trunk/src/c/classes/Elements/Penta.h

    r26744 r27035  
    4949                void           AddControlInput(int input_enum,Inputs* inputs,IoModel* iomodel,IssmDouble* values,IssmDouble* values_min,IssmDouble* values_max, int interpolation_enum,int id);
    5050                void           ControlInputExtrude(int enum_type,int start);
     51                void           ComputeSigmaVM(void);
    5152                void           DatasetInputExtrude(int enum_type,int start);
    5253                void           DatasetInputCreate(IssmDouble* array,int M,int N,int* individual_enums,int num_inputs,Inputs* inputs,IoModel* iomodel,int input_enum);
     
    169170                void           PotentialUngrounding(Vector<IssmDouble>* potential_sheet_ungrounding);
    170171                int            PressureInterpolation();
    171       void           Recover3DMLHOInput(int targetVel_enum, int numnodes, IssmDouble* vb,  IssmDouble* vsh, IssmDouble* n, IssmDouble* H, IssmDouble* s);
     172      void           Recover3DMOLHOInput(int targetVel_enum, int numnodes, IssmDouble* vb,  IssmDouble* vsh, IssmDouble* n, IssmDouble* H, IssmDouble* s);
    172173                void           ReduceMatrices(ElementMatrix* Ke,ElementVector* pe);
    173174                void           ResetFSBasalBoundaryCondition(void);
     
    225226                void       GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,Matlitho* litho, IssmDouble* x,IssmDouble* y){_error_("not implemented yet");};
    226227                void       SealevelchangeGeometrySubElementKernel(SealevelGeometry* slgeom){_error_("not implemented yet");};
    227                 void       SealevelchangeMomentOfInertiaCentroid(IssmDouble* dI_list, GrdLoads* loads,  SealevelGeometry* slgeom){_error_("not implemented yet");};
    228228                void       SealevelchangeShift(GrdLoads* loads,  IssmDouble offset, SealevelGeometry* slgeom){_error_("not implemented yet");};
    229229                void       SealevelchangeGeometryInitial(IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae){_error_("not implemented yet");};
     
    234234                void       SealevelchangeOceanAverage(GrdLoads* loads, Vector<IssmDouble>* oceanareas, Vector<IssmDouble>* subelementoceanareas, IssmDouble* sealevelpercpu, SealevelGeometry* slgeom){_error_("not implemented yet");};
    235235                void       SealevelchangeDeformationConvolution(IssmDouble* sealevelpercpu, GrdLoads* loads,  IssmDouble* rotationvector,SealevelGeometry* slgeom){_error_("not implemented yet");};
    236                 void       SealevelchangeMomentOfInertiaSubElement(IssmDouble* dI_list, GrdLoads* loads, SealevelGeometry* slgeom){_error_("not implemented yet");};
    237                 void       SealevelchangeUpdateViscousFields(){_error_("not implemented yet");};
     236                void       SealevelchangeUpdateViscousFields(IssmDouble lincoeff, int newindex, int offset){_error_("not implemented yet");};
    238237                #endif
    239238
  • issm/trunk/src/c/classes/Elements/Seg.h

    r26744 r27035  
    179179                void       GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt,Matlitho* litho, IssmDouble* x,IssmDouble* y){_error_("not implemented yet");};
    180180                void       SealevelchangeGeometrySubElementKernel(SealevelGeometry* slgeom){_error_("not implemented yet");};
    181                 void       SealevelchangeMomentOfInertiaCentroid(IssmDouble* dI_list, GrdLoads* loads,  SealevelGeometry* slgeom){_error_("not implemented yet");};
    182181                void       SealevelchangeShift(GrdLoads* loads, IssmDouble offset, SealevelGeometry* slgeom){_error_("not implemented yet");};
    183182                void       SealevelchangeGeometryInitial(IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae){_error_("not implemented yet");};
     
    188187                void       SealevelchangeOceanAverage(GrdLoads* loads, Vector<IssmDouble>* oceanareas, Vector<IssmDouble>* subelementoceanareas, IssmDouble* sealevelpercpu, SealevelGeometry* slgeom){_error_("not implemented yet");};
    189188                void       SealevelchangeDeformationConvolution(IssmDouble* sealevelpercpu, GrdLoads* loads, IssmDouble* rotationvector,SealevelGeometry* slgeom){_error_("not implemented yet");};
    190                 void       SealevelchangeMomentOfInertiaSubElement(IssmDouble* dI_list, GrdLoads* loads, SealevelGeometry* slgeom){_error_("not implemented yet");};
    191                 void       SealevelchangeUpdateViscousFields(){_error_("not implemented yet");};
     189                void       SealevelchangeUpdateViscousFields(IssmDouble lincoeff, int newindex, int offset){_error_("not implemented yet");};
    192190#endif
    193191
  • issm/trunk/src/c/classes/Elements/Tetra.cpp

    r26744 r27035  
    605605        norm=sqrt(normal[0]*normal[0]+normal[1]*normal[1]+normal[2]*normal[2]);
    606606
    607         for(int i=0;i<3;i++) normal[i]=normal[i]/norm;
     607        for(int i=0;i<3;i++) normal[i]=normal[i]/(norm+1e-10);
    608608}
    609609/*}}}*/
  • issm/trunk/src/c/classes/Elements/Tetra.h

    r26744 r27035  
    186186                void       GiaDeflection(Vector<IssmDouble>* wg,Vector<IssmDouble>* dwgdt, Matlitho* litho, IssmDouble* x,IssmDouble* y){_error_("not implemented yet");};
    187187                void       SealevelchangeGeometrySubElementKernel(SealevelGeometry* slgeom){_error_("not implemented yet");};
    188                 void       SealevelchangeMomentOfInertiaCentroid(IssmDouble* dI_list, GrdLoads* loads,  SealevelGeometry* slgeom){_error_("not implemented yet");};
    189188                void       SealevelchangeShift(GrdLoads* loads,  IssmDouble offset, SealevelGeometry* slgeom){_error_("not implemented yet");};
    190189                void       SealevelchangeGeometryInitial(IssmDouble* xxe, IssmDouble* yye, IssmDouble* zze, IssmDouble* areae){_error_("not implemented yet");};
     
    195194                void       SealevelchangeOceanAverage(GrdLoads* loads, Vector<IssmDouble>* oceanareas, Vector<IssmDouble>* subelementoceanareas, IssmDouble* sealevelpercpu, SealevelGeometry* slgeom){_error_("not implemented yet");};
    196195                void       SealevelchangeDeformationConvolution(IssmDouble* sealevelpercpu, GrdLoads* loads,  IssmDouble* rotationvector,SealevelGeometry* slgeom){_error_("not implemented yet");};
    197                 void       SealevelchangeMomentOfInertiaSubElement(IssmDouble* dI_list, GrdLoads* loads, SealevelGeometry* slgeom){_error_("not implemented yet");};
    198                 void       SealevelchangeUpdateViscousFields(){_error_("not implemented yet");};
     196                void       SealevelchangeUpdateViscousFields(IssmDouble lincoeff, int newindex, int offset){_error_("not implemented yet");};
    199197#endif
    200198
  • issm/trunk/src/c/classes/Elements/Tria.cpp

    r26744 r27035  
    2929#define NUMVERTICES   3
    3030#define NUMVERTICES1D 2
    31 //#define ISMICI        1
     31//#define MICI          1 //1 = DeConto & Pollard, 2 = DOMINOS
    3232
    3333/*Constructors/destructor/copy*/
     
    313313void       Tria::CalvingRateVonmises(){/*{{{*/
    314314
    315         IssmDouble  xyz_list[NUMVERTICES][3];
    316         IssmDouble  epsilon[3]; /* epsilon=[exx,eyy,exy];*/
    317         IssmDouble  calvingratex[NUMVERTICES];
    318         IssmDouble  calvingratey[NUMVERTICES];
     315        /*First, compute Von Mises Stress*/
     316        this->ComputeSigmaVM();
     317
     318        /*Now compute calving rate*/
    319319        IssmDouble  calvingrate[NUMVERTICES];
    320         IssmDouble  lambda1,lambda2,ex,ey,vx,vy,vel;
    321         IssmDouble  sigma_vm[NUMVERTICES];
    322         IssmDouble  B,sigma_max,sigma_max_floating,sigma_max_grounded,n;
    323         IssmDouble  epse_2,groundedice,bed,sealevel;            // added sealevel
    324 
    325         /* Get node coordinates and dof list: */
    326         ::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
     320        IssmDouble  sigma_vm,vx,vy;
     321        IssmDouble  sigma_max,sigma_max_floating,sigma_max_grounded,n;
     322        IssmDouble  groundedice,bed,sealevel;
    327323
    328324        /*Retrieve all inputs and parameters we will need*/
    329         Input* vx_input = this->GetInput(VxEnum); _assert_(vx_input);
    330         Input* vy_input = this->GetInput(VyEnum); _assert_(vy_input);
    331         Input* B_input  = this->GetInput(MaterialsRheologyBbarEnum);   _assert_(B_input);
    332         Input* gr_input = this->GetInput(MaskOceanLevelsetEnum); _assert_(gr_input);
    333         Input* bs_input = this->GetInput(BaseEnum);                    _assert_(bs_input);
    334         Input* smax_fl_input = this->GetInput(CalvingStressThresholdFloatingiceEnum); _assert_(smax_fl_input);
    335         Input* smax_gr_input = this->GetInput(CalvingStressThresholdGroundediceEnum); _assert_(smax_gr_input);
    336         Input* n_input  = this->GetInput(MaterialsRheologyNEnum); _assert_(n_input);
    337         Input* sl_input  = this->GetInput(SealevelEnum); _assert_(sl_input);
     325        Input* vx_input       = this->GetInput(VxEnum); _assert_(vx_input);
     326        Input* vy_input       = this->GetInput(VyEnum); _assert_(vy_input);
     327        Input* gr_input       = this->GetInput(MaskOceanLevelsetEnum); _assert_(gr_input);
     328        Input* bs_input       = this->GetInput(BaseEnum);                    _assert_(bs_input);
     329        Input* smax_fl_input  = this->GetInput(CalvingStressThresholdFloatingiceEnum); _assert_(smax_fl_input);
     330        Input* smax_gr_input  = this->GetInput(CalvingStressThresholdGroundediceEnum); _assert_(smax_gr_input);
     331        Input* sl_input       = this->GetInput(SealevelEnum); _assert_(sl_input);
     332        Input* sigma_vm_input = this->GetInput(SigmaVMEnum); _assert_(sigma_vm_input);
    338333
    339334        /* Start looping on the number of vertices: */
     
    343338
    344339                /*Get velocity components and thickness*/
    345                 B_input->GetInputValue(&B,&gauss);
    346                 n_input->GetInputValue(&n,&gauss);
     340                sigma_vm_input->GetInputValue(&sigma_vm,&gauss);
    347341                vx_input->GetInputValue(&vx,&gauss);
    348342                vy_input->GetInputValue(&vy,&gauss);
     
    351345                smax_fl_input->GetInputValue(&sigma_max_floating,&gauss);
    352346                smax_gr_input->GetInputValue(&sigma_max_grounded,&gauss);
    353                 vel=sqrt(vx*vx+vy*vy)+1.e-14;
    354347                sl_input->GetInputValue(&sealevel,&gauss);
    355 
    356                 /*Compute strain rate and viscosity: */
    357                 this->StrainRateSSA(&epsilon[0],&xyz_list[0][0],&gauss,vx_input,vy_input);
    358 
    359                 /*Get Eigen values*/
    360                 Matrix2x2Eigen(&lambda1,&lambda2,&ex,&ey,epsilon[0],epsilon[2],epsilon[1]);
    361                 _assert_(!xIsNan<IssmDouble>(lambda1));
    362                 _assert_(!xIsNan<IssmDouble>(lambda2));
    363 
    364                 /*Process Eigen values (only account for extension)*/
    365                 lambda1 = max(lambda1,0.);
    366                 lambda2 = max(lambda2,0.);
    367 
    368                 /*Calculate sigma_vm*/
    369                 epse_2    = 1./2. *(lambda1*lambda1 + lambda2*lambda2);
    370                 sigma_vm[iv]  = sqrt(3.) * B * pow(epse_2,1./(2.*n));
    371 
    372                 /*OLD (keep for a little bit)*/
    373                 //sigma_max = 800.e+3; //IUGG previous test
    374                 //sigma_max = 1000.e+3; //GRL
    375                 //if(groundedice<0) sigma_max=150.e+3;
    376348
    377349                /*Tensile stress threshold*/
     
    380352                else
    381353                 sigma_max = sigma_max_grounded;
     354
    382355                /*Assign values*/
    383                 if(bed>sealevel){               // Changed 0. to sealevel
    384                         calvingratex[iv]=0.;
    385                         calvingratey[iv]=0.;
     356                if(bed>sealevel){
     357                        calvingrate[iv] = 0.;
    386358                }
    387359                else{
    388                         calvingratex[iv]=vx*sigma_vm[iv]/sigma_max;
    389                         calvingratey[iv]=vy*sigma_vm[iv]/sigma_max;
    390                 }
    391                 calvingrate[iv] =sqrt(calvingratex[iv]*calvingratex[iv] + calvingratey[iv]*calvingratey[iv]);
    392 
     360                        calvingrate[iv] = sqrt(vx*vx+vy*vy)*sigma_vm/sigma_max;
     361                }
     362        }
     363
     364        /*Add input*/
     365        this->AddInput(CalvingCalvingrateEnum,&calvingrate[0],P1DGEnum);
     366   this->CalvingFromRate();
     367}
     368/*}}}*/
     369void       Tria::CalvingRateTest(){/*{{{*/
     370
     371        IssmDouble  calvingratex[NUMVERTICES];
     372        IssmDouble  calvingratey[NUMVERTICES];
     373        IssmDouble  calvingrate[NUMVERTICES];
     374        IssmDouble  vx,vy,vel;
     375        IssmDouble  dphidx, dphidy, dphi;
     376        IssmDouble  time;
     377        IssmDouble  coeff, indrate;
     378
     379        /*Retrieve all inputs and parameters we will need*/
     380        parameters->FindParam(&time,TimeEnum);
     381        parameters->FindParam(&coeff,CalvingTestSpeedfactorEnum,time);
     382        parameters->FindParam(&indrate,CalvingTestIndependentRateEnum,time);
     383
     384        Input* vx_input = this->GetInput(VxEnum); _assert_(vx_input);
     385        Input* vy_input = this->GetInput(VyEnum); _assert_(vy_input);
     386        Input *lsf_slopex_input  = this->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
     387   Input *lsf_slopey_input  = this->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
     388
     389        /* Start looping on the number of vertices: */
     390        GaussTria gauss;
     391        for(int iv=0;iv<NUMVERTICES;iv++){
     392                gauss.GaussVertex(iv);
     393
     394                /*Get velocity components and thickness*/
     395                vx_input->GetInputValue(&vx,&gauss);
     396                vy_input->GetInputValue(&vy,&gauss);
     397
     398                lsf_slopex_input->GetInputValue(&dphidx,&gauss);
     399      lsf_slopey_input->GetInputValue(&dphidy,&gauss);
     400
     401      vel=sqrt(vx*vx + vy*vy) + 1e-14;
     402      dphi=sqrt(dphidx*dphidx+dphidy*dphidy)+ 1e-14;
     403
     404                calvingratex[iv]= coeff*vx + indrate*dphidx/dphi;
     405                calvingratey[iv]= coeff*vy + indrate*dphidy/dphi;
     406                calvingrate[iv] = sqrt(calvingratex[iv]*calvingratex[iv] + calvingratey[iv]*calvingratey[iv]);
    393407        }
    394408
     
    397411        this->AddInput(CalvingrateyEnum,&calvingratey[0],P1DGEnum);
    398412        this->AddInput(CalvingCalvingrateEnum,&calvingrate[0],P1DGEnum);
    399         this->AddInput(SigmaVMEnum,&sigma_vm[0],P1DGEnum);
    400413}
    401414/*}}}*/
     
    655668                IssmDouble calvingratex,calvingratey,thickness,Jdet,flux_per_area;
    656669                IssmDouble rho_ice=FindParam(MaterialsRhoIceEnum);
    657                 Input* thickness_input=this->GetInput(ThicknessEnum); _assert_(thickness_input);
    658                 Input* calvingratex_input=NULL;
    659                 Input* calvingratey_input=NULL;
    660                 if(domaintype==Domain2DhorizontalEnum){
    661                         calvingratex_input=this->GetInput(CalvingratexEnum); _assert_(calvingratex_input);
    662                         calvingratey_input=this->GetInput(CalvingrateyEnum); _assert_(calvingratey_input);
    663                 }
    664                 else{
    665                         calvingratex_input=this->GetInput(CalvingratexAverageEnum); _assert_(calvingratex_input);
    666                         calvingratey_input=this->GetInput(CalvingrateyAverageEnum); _assert_(calvingratey_input);
    667                 }
     670                Input* thickness_input    = this->GetInput(ThicknessEnum); _assert_(thickness_input);
     671                Input* calvingratex_input = this->GetInput(CalvingratexEnum); _assert_(calvingratex_input);
     672                Input* calvingratey_input = this->GetInput(CalvingrateyEnum); _assert_(calvingratey_input);
    668673
    669674                /*Start looping on Gaussian points*/
     
    789794                IssmDouble calvingratex,calvingratey,vx,vy,vel,meltingrate,meltingratex,meltingratey,thickness,Jdet,flux_per_area;
    790795                IssmDouble rho_ice=FindParam(MaterialsRhoIceEnum);
    791                 Input* thickness_input=this->GetInput(ThicknessEnum); _assert_(thickness_input);
    792                 Input* calvingratex_input=NULL;
    793                 Input* calvingratey_input=NULL;
    794                 Input* vx_input=NULL;
    795                 Input* vy_input=NULL;
    796                 Input* meltingrate_input=NULL;
    797                 if(domaintype==Domain2DhorizontalEnum){
    798                         calvingratex_input=this->GetInput(CalvingratexEnum); _assert_(calvingratex_input);
    799                         calvingratey_input=this->GetInput(CalvingrateyEnum); _assert_(calvingratey_input);
    800                         vx_input=this->GetInput(VxEnum); _assert_(vx_input);
    801                         vy_input=this->GetInput(VyEnum); _assert_(vy_input);
    802                         meltingrate_input=this->GetInput(CalvingMeltingrateEnum); _assert_(meltingrate_input);
    803                 }
    804                 else{
    805                         calvingratex_input=this->GetInput(CalvingratexAverageEnum); _assert_(calvingratex_input);
    806                         calvingratey_input=this->GetInput(CalvingrateyAverageEnum); _assert_(calvingratey_input);
    807                 }
     796                Input* thickness_input    = this->GetInput(ThicknessEnum); _assert_(thickness_input);
     797                Input* calvingratex_input = this->GetInput(CalvingratexEnum); _assert_(calvingratex_input);
     798                Input* calvingratey_input = this->GetInput(CalvingrateyEnum); _assert_(calvingratey_input);
     799                Input* vx_input           = this->GetInput(VxEnum); _assert_(vx_input);
     800                Input* vy_input           = this->GetInput(VyEnum); _assert_(vy_input);
     801                Input* meltingrate_input  = this->GetInput(CalvingMeltingrateEnum); _assert_(meltingrate_input);
    808802
    809803                /*Start looping on Gaussian points*/
     
    832826                delete gauss;
    833827        }
     828}
     829/*}}}*/
     830void       Tria::CalvingRateParameterization(){/*{{{*/
     831
     832        IssmDouble  xyz_list[NUMVERTICES][3];
     833        IssmDouble  epsilon[3]; /* epsilon=[exx,eyy,exy];*/
     834        IssmDouble  calvingrate[NUMVERTICES];
     835        IssmDouble  lambda1,lambda2,ex,ey,vx,vy,vel;
     836        IssmDouble  sigma_vm[NUMVERTICES];
     837        IssmDouble  B,sigma_max,sigma_max_floating,sigma_max_grounded,n;
     838        IssmDouble  epse_2,groundedice,bed,sealevel;
     839        IssmDouble  arate, rho_ice, rho_water, thickness, paramX, Hab;
     840        int                     use_parameter=0;
     841        int                     nonlinear_law=0;
     842        IssmDouble  theta, alpha, midp, gamma;
     843
     844        /* Get node coordinates and dof list: */
     845        ::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
     846
     847        /*Retrieve all inputs and parameters we will need*/
     848        Input *vx_input      = this->GetInput(VxEnum);                                _assert_(vx_input);
     849        Input *vy_input      = this->GetInput(VyEnum);                                _assert_(vy_input);
     850        Input *B_input       = this->GetInput(MaterialsRheologyBbarEnum);             _assert_(B_input);
     851        Input *gr_input      = this->GetInput(MaskOceanLevelsetEnum);                 _assert_(gr_input);
     852        Input *bs_input      = this->GetInput(BedEnum);                               _assert_(bs_input);
     853        Input *H_input       = this->GetInput(ThicknessEnum);                         _assert_(H_input);
     854        Input *smax_fl_input = this->GetInput(CalvingStressThresholdFloatingiceEnum); _assert_(smax_fl_input);
     855        Input *smax_gr_input = this->GetInput(CalvingStressThresholdGroundediceEnum); _assert_(smax_gr_input);
     856        Input *n_input       = this->GetInput(MaterialsRheologyNEnum);                _assert_(n_input);
     857        Input *sl_input      = this->GetInput(SealevelEnum);                          _assert_(sl_input);
     858        Input *arate_input   = this->GetInput(CalvingAblationrateEnum);               _assert_(arate_input);
     859
     860        /* Ice and sea water density */
     861        this->FindParam(&rho_ice,MaterialsRhoIceEnum);
     862        this->FindParam(&rho_water,MaterialsRhoSeawaterEnum);
     863
     864        /* Use which parameter  */
     865        this->FindParam(&use_parameter, CalvingUseParamEnum);
     866        this->FindParam(&theta, CalvingScaleThetaEnum);
     867        this->FindParam(&alpha, CalvingAmpAlphaEnum);
     868        this->FindParam(&midp, CalvingMidpointEnum);
     869        this->FindParam(&nonlinear_law, CalvingNonlinearLawEnum);
     870
     871        /* Start looping on the number of vertices: */
     872        GaussTria* gauss=new GaussTria();
     873        for(int iv=0;iv<NUMVERTICES;iv++){
     874                gauss->GaussVertex(iv);
     875
     876                /*Get velocity components and thickness*/
     877                B_input->GetInputValue(&B,gauss);
     878                n_input->GetInputValue(&n,gauss);
     879                vx_input->GetInputValue(&vx,gauss);
     880                vy_input->GetInputValue(&vy,gauss);
     881                gr_input->GetInputValue(&groundedice,gauss);
     882                bs_input->GetInputValue(&bed,gauss);
     883                H_input->GetInputValue(&thickness,gauss);
     884                smax_fl_input->GetInputValue(&sigma_max_floating,gauss);
     885                smax_gr_input->GetInputValue(&sigma_max_grounded,gauss);
     886                vel=sqrt(vx*vx+vy*vy)+1.e-14;
     887                sl_input->GetInputValue(&sealevel,gauss);
     888                arate_input->GetInputValue(&arate,gauss);
     889
     890                /*Compute strain rate and viscosity: */
     891                this->StrainRateSSA(&epsilon[0],&xyz_list[0][0],gauss,vx_input,vy_input);
     892
     893                /*Get Eigen values*/
     894                Matrix2x2Eigen(&lambda1,&lambda2,&ex,&ey,epsilon[0],epsilon[2],epsilon[1]);
     895                _assert_(!xIsNan<IssmDouble>(lambda1));
     896                _assert_(!xIsNan<IssmDouble>(lambda2));
     897
     898                /*Process Eigen values (only account for extension)*/
     899                lambda1 = max(lambda1,0.);
     900                lambda2 = max(lambda2,0.);
     901
     902                /*Calculate sigma_vm*/
     903                epse_2    = 1./2. *(lambda1*lambda1 + lambda2*lambda2);
     904                sigma_vm[iv]  = sqrt(3.) * B * pow(epse_2,1./(2.*n));
     905
     906                /*Tensile stress threshold*/
     907                if(groundedice<0)
     908                 sigma_max = sigma_max_floating;
     909                else
     910                 sigma_max = sigma_max_grounded;
     911
     912                switch (use_parameter) {
     913                        case 0:
     914                                /* bed elevation */
     915                                paramX = bed;
     916                                break;
     917                        case 1:
     918                                /* Height above floatation */
     919                                if (bed>sealevel)       paramX = 0.0;
     920                                else paramX = thickness - (rho_water/rho_ice) * (sealevel-bed);
     921                                break;
     922                        case 2:
     923                                /* Thicknese */
     924                                paramX = thickness;
     925                                break;
     926                        case 4:
     927                                /* bed elevation+linear curve fitting */
     928                                paramX = bed;
     929                                break;
     930                        case -1:
     931                                /* use nothing, just the arate*/
     932                                break;
     933                        default:
     934                                _error_("The parameter is not supported yet!");
     935                }
     936
     937                /* Compute the hyperbolic tangent function */
     938                if ((use_parameter>-0.5) & (use_parameter<3)) {
     939                        gamma = 0.5*theta*(1.0-tanh((paramX+midp)/alpha))+(1.0-theta);
     940                        if (gamma<0.0) gamma =0.0;
     941                }
     942                else if (use_parameter>=3) {
     943                        gamma = alpha*paramX + theta;
     944                        if (gamma > 1.0) gamma = 1.0;
     945                        if (gamma < 0.0) gamma = 0.0;
     946                }
     947                else gamma = 1;
     948
     949                /*-------------------------------------------*/
     950                if (nonlinear_law) {
     951                        /*This von Mises type has too strong positive feedback with vel included
     952                         * calvingrate[iv] = (arate+sigma_vm[iv]*vel/sigma_max)*gamma;
     953                         */
     954                        Hab = thickness - (rho_water/rho_ice) * (sealevel-bed);
     955                        if (Hab < 0.) Hab = 0.;
     956                        if (bed > sealevel) Hab = 0.;
     957
     958                        calvingrate[iv] = (arate+Hab/sigma_max)*gamma;
     959                }
     960                else {
     961                        calvingrate[iv] = arate*gamma;
     962                }
     963        }
     964
     965        /*Add input*/
     966        this->AddInput(CalvingCalvingrateEnum,&calvingrate[0],P1DGEnum);
     967        this->AddInput(SigmaVMEnum,&sigma_vm[0],P1DGEnum);
     968        this->CalvingFromRate();
     969
     970        /*Clean up and return*/
     971        delete gauss;
    834972}
    835973/*}}}*/
     
    9141052}
    9151053/*}}}*/
    916 void         Tria::ComputeEsaStrainAndVorticity(){ /*{{{*/
     1054void          Tria::ComputeEsaStrainAndVorticity(){ /*{{{*/
    9171055
    9181056        IssmDouble  xyz_list[NUMVERTICES][3];
     
    10101148                delete gauss;
    10111149        }
     1150}
     1151/*}}}*/
     1152void       Tria::ComputeSigmaVM(){/*{{{*/
     1153
     1154        IssmDouble  xyz_list[NUMVERTICES][3];
     1155        IssmDouble  epsilon[3]; /* epsilon=[exx,eyy,exy];*/
     1156        IssmDouble  lambda1,lambda2,ex,ey,vx,vy,vel;
     1157        IssmDouble  sigma_vm[NUMVERTICES];
     1158        IssmDouble  B,n;
     1159
     1160        /* Get node coordinates and dof list: */
     1161        ::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
     1162
     1163        /*Retrieve all inputs and parameters we will need*/
     1164        Input* vx_input = this->GetInput(VxEnum); _assert_(vx_input);
     1165        Input* vy_input = this->GetInput(VyEnum); _assert_(vy_input);
     1166        Input* B_input  = this->GetInput(MaterialsRheologyBbarEnum);   _assert_(B_input);
     1167        Input* n_input  = this->GetInput(MaterialsRheologyNEnum); _assert_(n_input);
     1168
     1169        /* Start looping on the number of vertices: */
     1170        GaussTria gauss;
     1171        for(int iv=0;iv<NUMVERTICES;iv++){
     1172                gauss.GaussVertex(iv);
     1173
     1174                /*Get velocity components and thickness*/
     1175                B_input->GetInputValue(&B,&gauss);
     1176                n_input->GetInputValue(&n,&gauss);
     1177                vx_input->GetInputValue(&vx,&gauss);
     1178                vy_input->GetInputValue(&vy,&gauss);
     1179                vel=sqrt(vx*vx+vy*vy)+1.e-14;
     1180
     1181                /*Compute strain rate and viscosity: */
     1182                this->StrainRateSSA(&epsilon[0],&xyz_list[0][0],&gauss,vx_input,vy_input);
     1183
     1184                /*Get Eigen values*/
     1185                Matrix2x2Eigen(&lambda1,&lambda2,&ex,&ey,epsilon[0],epsilon[2],epsilon[1]);
     1186                _assert_(!xIsNan<IssmDouble>(lambda1));
     1187                _assert_(!xIsNan<IssmDouble>(lambda2));
     1188
     1189                /*Process Eigen values (only account for extension)*/
     1190                lambda1 = max(lambda1,0.);
     1191                lambda2 = max(lambda2,0.);
     1192
     1193                /*Calculate sigma_vm*/
     1194                IssmDouble epse_2 = 1./2. *(lambda1*lambda1 + lambda2*lambda2);
     1195                sigma_vm[iv]  = sqrt(3.) * B * pow(epse_2,1./(2.*n));
     1196        }
     1197
     1198        /*Add input*/
     1199        this->AddInput(SigmaVMEnum,&sigma_vm[0],P1DGEnum);
    10121200}
    10131201/*}}}*/
     
    19372125        //compute sea level load weights
    19382126        this->GetFractionGeometry(loadweights,&phi,&point1,&fraction1,&fraction2,&istrapeze1,levelset);
    1939 
     2127        for (int i=0;i<NUMVERTICES;i++) loadweights[i]/=phi;
    19402128        this->GetBarycenterFromLevelset(platbar,plongbar, phi, fraction1, fraction2, late, longe, point1,istrapeze1,planetradius);
    19412129
     
    20282216                this->GetFractionGeometry(loadweights,&phi2,&point2,&f,&g,&istrapeze2,levelset2);
    20292217                this->GetBarycenterFromLevelset(platbar,plongbar, phi2, f, g, late, longe, point2,istrapeze2,planetradius);
     2218                for (int i=0;i<NUMVERTICES;i++) loadweights[i]/=phi2;
    20302219                *ploadarea=area*phi2;
    20312220                return;
     
    20342223                this->GetFractionGeometry(loadweights,&phi1,&point1,&d,&e,&istrapeze1,levelset1);
    20352224                this->GetBarycenterFromLevelset(platbar,plongbar, phi1, d, e, late, longe, point1,istrapeze1,planetradius);
     2225                for (int i=0;i<NUMVERTICES;i++) loadweights[i]/=phi1;
    20362226                *ploadarea=area*phi1;
    20372227                return;
     
    20462236                this->GetBarycenterFromLevelset(platbar,plongbar, phi1, d, e, late, longe, point1,istrapeze1,planetradius);
    20472237                *ploadarea=area*phi1;
    2048                 for (int i=0;i<NUMVERTICES;i++) loadweights[i]=weights1[i];
     2238                for (int i=0;i<NUMVERTICES;i++) loadweights[i]=weights1[i]/phi1;
    20492239                return;
    20502240        }
     
    21072297
    21082298        //interpolant weights of each point. Any field F[0,1,2] provided at the original vertices [0,1,2] will be equal on point k to sum_i (F[i] * w[k][i])
    2109         w[0][0]=1; //A
    2110         w[1][1]=1; //B
    2111         w[2][2]=1; //C
     2299        w[i0][i0]=1; //A
     2300        w[i1][i1]=1; //B
     2301        w[i2][i2]=1; //C
    21122302        w[3][i0]=1.0-d; w[3][i1]=d; //D
    21132303        w[4][i0]=1.0-e; w[4][i2]=e; //E
     
    23312521                for (int j=0;j<3;j++){
    23322522                        for (int i=0;i<NUMVERTICES;i++) {
    2333                                 loadweights[j]=w1[i][j]*area1 + w2[i][j]*area2 + w3[i][j]*area3;
     2523                                loadweights[j]+=w1[i][j]*area1 + w2[i][j]*area2 + w3[i][j]*area3;
    23342524                                barycenter[j]+=xyz1[i][j]*area1+xyz2[i][j]*area2+xyz3[i][j]*area3;
    23352525                        }
    2336                         loadweights[j]/=area;
     2526                        loadweights[j]/=areasub*3.0;
    23372527                        barycenter[j]/=areasub *3.0;
    23382528                }
     
    26042794                                input->Serve(numindices,&indices[0]);
    26052795                                break;
     2796                        case P1xP2Enum:
     2797                        case P1xP3Enum:
    26062798                        case P1xP4Enum:
    26072799                        case P1DGEnum:
     
    35963788        }
    35973789
    3598        
    35993790        /*Cleanup & return: */
    36003791        xDelete<int>(indices);
     
    41014292        IssmDouble norm_dlsf, norm_calving, calvingrate, meltingrate, groundedice;
    41024293        IssmDouble migrationmax, calvinghaf, heaviside, haf_eps;
    4103         IssmDouble  xyz_list[NUMVERTICES][3];
    4104         IssmDouble  movingfrontvx[NUMVERTICES];
    4105         IssmDouble  movingfrontvy[NUMVERTICES];
    4106         IssmDouble  vel;
     4294        IssmDouble xyz_list[NUMVERTICES][3];
     4295        IssmDouble movingfrontvx[NUMVERTICES];
     4296        IssmDouble movingfrontvy[NUMVERTICES];
     4297        IssmDouble vel;
    41074298
    41084299        /* Get node coordinates and dof list: */
    41094300        ::GetVerticesCoordinates(&xyz_list[0][0],vertices,NUMVERTICES);
    41104301
    4111         Input* vx_input           = NULL;
    4112         Input* vy_input           = NULL;
    41134302        Input* calvingratex_input = NULL;
    41144303        Input* calvingratey_input = NULL;
    4115         Input* lsf_slopex_input   = NULL;
    4116         Input* lsf_slopey_input   = NULL;
    41174304        Input* calvingrate_input  = NULL;
    41184305        Input* meltingrate_input  = NULL;
    4119         Input* gr_input           = NULL;
    41204306
    41214307        /*Get problem dimension and whether there is moving front or not*/
     
    41294315                default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
    41304316        }
    4131         /*Load velocities*/
    4132         switch(domaintype){
    4133                 case Domain2DverticalEnum:
    4134                         vx_input=this->GetInput(VxEnum); _assert_(vx_input);
    4135                         break;
    4136                 case Domain2DhorizontalEnum:
    4137                         vx_input=this->GetInput(VxEnum); _assert_(vx_input);
    4138                         vy_input=this->GetInput(VyEnum); _assert_(vy_input);
    4139                         gr_input=this->GetInput(MaskOceanLevelsetEnum); _assert_(gr_input);
    4140                         break;
    4141                 case Domain3DEnum:
    4142                         vx_input=this->GetInput(VxAverageEnum); _assert_(vx_input);
    4143                         vy_input=this->GetInput(VyAverageEnum); _assert_(vy_input);
    4144                         gr_input=this->GetInput(MaskOceanLevelsetEnum); _assert_(gr_input);
    4145                         break;
    4146                 default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
    4147         }
     4317
     4318        /*Load levelset function gradients*/
     4319   Input *gr_input         = this->GetInput(MaskOceanLevelsetEnum); _assert_(gr_input);
     4320        Input *lsf_slopex_input = this->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
     4321        Input *lsf_slopey_input = this->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
     4322        Input *vx_input         = this->GetInput(VxEnum);                     _assert_(vx_input);
     4323        Input *vy_input         = this->GetInput(VyEnum); _assert_(vy_input);
    41484324
    41494325        switch(calvinglaw){
    41504326                case DefaultCalvingEnum:
    41514327                case CalvingVonmisesEnum:
    4152                         lsf_slopex_input  = this->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
    4153                         if(dim==2) lsf_slopey_input  = this->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
    4154                         calvingrate_input = this->GetInput(CalvingCalvingrateEnum);     _assert_(calvingrate_input);
    4155                         meltingrate_input = this->GetInput(CalvingMeltingrateEnum);     _assert_(meltingrate_input);
    4156                         break;
    41574328                case CalvingLevermannEnum:
    4158                         switch(domaintype){
    4159                                 case Domain2DverticalEnum:
    4160                                         calvingratex_input=this->GetInput(CalvingratexEnum); _assert_(calvingratex_input);
    4161                                         break;
    4162                                 case Domain2DhorizontalEnum:
    4163                                         calvingratex_input=this->GetInput(CalvingratexEnum); _assert_(calvingratex_input);
    4164                                         calvingratey_input=this->GetInput(CalvingrateyEnum); _assert_(calvingratey_input);
    4165                                         break;
    4166                                 case Domain3DEnum:
    4167                                         calvingratex_input=this->GetInput(CalvingratexAverageEnum); _assert_(calvingratex_input);
    4168                                         calvingratey_input=this->GetInput(CalvingrateyAverageEnum); _assert_(calvingratey_input);
    4169                                         break;
    4170                                 default: _error_("mesh "<<EnumToStringx(domaintype)<<" not supported yet");
    4171                         }
     4329                case CalvingTestEnum:
     4330                case CalvingParameterizationEnum:
     4331                        calvingratex_input=this->GetInput(CalvingratexEnum); _assert_(calvingratex_input);
     4332                        calvingratey_input=this->GetInput(CalvingrateyEnum); _assert_(calvingratey_input);
    41724333                        meltingrate_input = this->GetInput(CalvingMeltingrateEnum);     _assert_(meltingrate_input);
    41734334                        break;
    41744335                case CalvingMinthicknessEnum:
    4175                         lsf_slopex_input  = this->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
    4176                         if(dim==2) lsf_slopey_input  = this->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
    4177                         meltingrate_input = this->GetInput(CalvingMeltingrateEnum);     _assert_(meltingrate_input);
    4178                         break;
    41794336                case CalvingHabEnum:
    4180                         lsf_slopex_input  = this->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
    4181                         if(dim==2) lsf_slopey_input  = this->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
    4182                         meltingrate_input = this->GetInput(CalvingMeltingrateEnum);     _assert_(meltingrate_input);
    4183                         break;
    41844337                case CalvingCrevasseDepthEnum:
    4185                         lsf_slopex_input  = this->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
    4186                         if(dim==2) lsf_slopey_input  = this->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
    41874338                        meltingrate_input = this->GetInput(CalvingMeltingrateEnum);     _assert_(meltingrate_input);
    41884339                        break;
    41894340                case CalvingDev2Enum:
    41904341                        this->FindParam(&calvinghaf,CalvingHeightAboveFloatationEnum);
    4191                         lsf_slopex_input  = this->GetInput(LevelsetfunctionSlopeXEnum); _assert_(lsf_slopex_input);
    4192                         if(dim==2) lsf_slopey_input  = this->GetInput(LevelsetfunctionSlopeYEnum); _assert_(lsf_slopey_input);
    41934342                        calvingrate_input = this->GetInput(CalvingCalvingrateEnum);     _assert_(calvingrate_input);
    41944343                        meltingrate_input = this->GetInput(CalvingMeltingrateEnum);     _assert_(meltingrate_input);
     
    42074356                vy_input->GetInputValue(&v[1],&gauss);
    42084357                gr_input->GetInputValue(&groundedice,&gauss);
     4358                lsf_slopex_input->GetInputValue(&dlsf[0],&gauss);
     4359                if(dim==2) lsf_slopey_input->GetInputValue(&dlsf[1],&gauss);
     4360
     4361                norm_dlsf=0.;
     4362                for(i=0;i<dim;i++) norm_dlsf+=pow(dlsf[i],2);
     4363                norm_dlsf=sqrt(norm_dlsf);
    42094364
    42104365                /*Get calving speed*/
     
    42124367                        case DefaultCalvingEnum:
    42134368                        case CalvingVonmisesEnum:
    4214                                 lsf_slopex_input->GetInputValue(&dlsf[0],&gauss);
    4215                                 if(dim==2) lsf_slopey_input->GetInputValue(&dlsf[1],&gauss);
    4216                                 calvingrate_input->GetInputValue(&calvingrate,&gauss);
     4369                        case CalvingTestEnum:
     4370                        case CalvingParameterizationEnum:
     4371                                calvingratex_input->GetInputValue(&c[0],&gauss);
     4372                                calvingratey_input->GetInputValue(&c[1],&gauss);
    42174373                                meltingrate_input->GetInputValue(&meltingrate,&gauss);
    42184374                                if(groundedice<0) meltingrate = 0.;
    4219 
    4220                                 norm_dlsf=0.;
    4221                                 for(i=0;i<dim;i++) norm_dlsf+=pow(dlsf[i],2);
    4222                                 norm_dlsf=sqrt(norm_dlsf);
    4223 
    4224                                 if(norm_dlsf>1.e-10)
    4225                                  for(i=0;i<dim;i++){
    4226                                          c[i]=calvingrate*dlsf[i]/norm_dlsf; m[i]=meltingrate*dlsf[i]/norm_dlsf;
    4227                                  }
    4228                                 else
    4229                                  for(i=0;i<dim;i++){
    4230                                          c[i]=0.; m[i]=0.;
    4231                                  }
     4375                                m[0]=meltingrate*dlsf[0]/norm_dlsf;
     4376                                m[1]=meltingrate*dlsf[1]/norm_dlsf;
     4377
     4378                                if(norm_dlsf<1.e-10){
     4379                                        for(i=0;i<dim;i++){
     4380                                                c[i]=0.; m[i]=0.;
     4381                                        }
     4382                                }
    42324383                                break;
    42334384
     
    42434394
    42444395                        case CalvingMinthicknessEnum:
    4245                                 lsf_slopex_input->GetInputValue(&dlsf[0],&gauss);
    4246                                 if(dim==2) lsf_slopey_input->GetInputValue(&dlsf[1],&gauss);
     4396                        case CalvingHabEnum:
     4397                        case CalvingCrevasseDepthEnum:
    42474398                                meltingrate_input->GetInputValue(&meltingrate,&gauss);
    4248 
    4249                                 norm_dlsf=0.;
    4250                                 for(i=0;i<dim;i++) norm_dlsf+=pow(dlsf[i],2);
    4251                                 norm_dlsf=sqrt(norm_dlsf);
    42524399
    42534400                                if(norm_dlsf>1.e-10)
     
    42634410                                break;
    42644411
    4265                         case CalvingHabEnum:
    4266                                 lsf_slopex_input->GetInputValue(&dlsf[0],&gauss);
    4267                                 if(dim==2) lsf_slopey_input->GetInputValue(&dlsf[1],&gauss);
    4268                                 meltingrate_input->GetInputValue(&meltingrate,&gauss);
    4269 
    4270                                 norm_dlsf=0.;
    4271                                 for(i=0;i<dim;i++) norm_dlsf+=pow(dlsf[i],2);
    4272                                 norm_dlsf=sqrt(norm_dlsf);
    4273 
    4274                                 if(norm_dlsf>1.e-10)
    4275                                  for(i=0;i<dim;i++){
    4276                                          c[i]=0.;
    4277                                          m[i]=meltingrate*dlsf[i]/norm_dlsf;
    4278                                  }
    4279                                 else
    4280                                  for(i=0;i<dim;i++){
    4281                                          c[i]=0.;
    4282                                          m[i]=0.;
    4283                                  }
    4284                                 break;
    4285 
    4286                         case CalvingCrevasseDepthEnum:
    4287                                 lsf_slopex_input->GetInputValue(&dlsf[0],&gauss);
    4288                                 if(dim==2) lsf_slopey_input->GetInputValue(&dlsf[1],&gauss);
    4289                                 meltingrate_input->GetInputValue(&meltingrate,&gauss);
    4290 
    4291                                 if(groundedice<0) meltingrate = 0.;
    4292 
    4293                                 norm_dlsf=0.;
    4294                                 for(i=0;i<dim;i++) norm_dlsf+=pow(dlsf[i],2);
    4295                                 norm_dlsf=sqrt(norm_dlsf);
    4296 
    4297                                 if(norm_dlsf>1.e-10)
    4298                                  for(i=0;i<dim;i++){
    4299                                          c[i]=0.;
    4300                                          m[i]=meltingrate*dlsf[i]/norm_dlsf;
    4301                                  }
    4302                                 else
    4303                                  for(i=0;i<dim;i++){
    4304                                          c[i]=0.;
    4305                                          m[i]=0.;
    4306                                  }
    4307                                 break;
    4308 
    43094412                        case CalvingDev2Enum:
    43104413                                  {
    4311                                         lsf_slopex_input->GetInputValue(&dlsf[0],&gauss);
    4312                                         if(dim==2) lsf_slopey_input->GetInputValue(&dlsf[1],&gauss);
    43134414                                        calvingrate_input->GetInputValue(&calvingrate,&gauss);
    43144415                                        meltingrate_input->GetInputValue(&meltingrate,&gauss);
     
    43354436                                        }
    43364437
    4337                                         norm_dlsf=0.;
    4338                                         for(i=0;i<dim;i++) norm_dlsf+=pow(dlsf[i],2);
    4339                                         norm_dlsf=sqrt(norm_dlsf);
    4340 
    43414438                                        if(norm_dlsf>1.e-10)
    43424439                                         for(i=0;i<dim;i++){
     
    43514448                                        break;
    43524449                                  }
     4450                                calvingratex_input->GetInputValue(&c[0],&gauss);
     4451                                if(dim==2) calvingratey_input->GetInputValue(&c[1],&gauss);
     4452                                for(i=0;i<dim;i++) m[i]=0.;
     4453                                break;
    43534454
    43544455                        default:
     
    43814482                ls_input->GetInputValue(&ls,&gauss);
    43824483
    4383                 /*Do we assume that the calving front does not move?*/
    4384                 //movingfrontvx[iv] = 0.;
    4385                 //movingfrontvy[iv] = 0.;
    4386 
    4387                 //if(Hc>80. && bed<0. && fabs(ls)<100.e3){ //Pollard & De Conto
    4388                 if(Hc>135. && bed<0. && fabs(ls)<100.e3){ // Crawford et all
    4389 
    4390                         lsf_slopex_input->GetInputValue(&dlsf[0],&gauss);
    4391                         norm_dlsf=0.;
    4392                         for(i=0;i<dim;i++) norm_dlsf+=pow(dlsf[i],2);
    4393                         norm_dlsf=sqrt(norm_dlsf);
    4394 
    4395                         /*use vel direction instead of LSF*/
    4396                         vx_input->GetInputValue(&v[0],&gauss);
    4397                         vy_input->GetInputValue(&v[1],&gauss);
    4398                         vel=sqrt(v[0]*v[0] + v[1]*v[1]);
    4399                         norm_dlsf = max(vel,1.e-10);
    4400                         dlsf[0] = v[0];
    4401                         dlsf[1] = v[1];
     4484                /*use vel direction instead of LSF*/
     4485                vx_input->GetInputValue(&v[0],&gauss);
     4486                vy_input->GetInputValue(&v[1],&gauss);
     4487                vel=sqrt(v[0]*v[0] + v[1]*v[1]);
     4488                norm_dlsf = max(vel,1.e-10);
     4489                dlsf[0] = v[0];
     4490                dlsf[1] = v[1];
     4491
     4492                /*Do we assume that the calving front does not move if MICI is not engaged?*/
     4493                movingfrontvx[iv] = 0.;
     4494                movingfrontvy[iv] = 0.;
     4495                //movingfrontvx[iv] = -2000./(365*24*3600.)*dlsf[0]/norm_dlsf;
     4496                //movingfrontvy[iv] = -2000./(365*24*3600.)*dlsf[1]/norm_dlsf;
     4497
     4498                if(MICI==1 && Hc>80. && bed<0. && fabs(ls)<100.e3){ //Pollard & De Conto
     4499                        IssmDouble C = (min(max(Hc,80.),100.) - 80.)/20. * 10./(24*3600.); /*Original MICI! convert from m/day to m/s*/
     4500
     4501                        /*Front motion = ice speed (v) - calving rate*/
     4502                        movingfrontvx[iv] = v[0]-C*dlsf[0]/norm_dlsf;
     4503                        movingfrontvy[iv] = v[1]-C*dlsf[1]/norm_dlsf;
     4504                }
     4505                else if (MICI==2 && Hc>135. && bed<0. && fabs(ls)<100.e3){ // Crawford et all
    44024506
    44034507                        /*5C Bn (worst case scenario)*/
     
    44054509                        IssmDouble alpha = 7.3;
    44064510                        IssmDouble C = min(2000.,I*pow(Hc,alpha))/(24*3600.); /*convert from m/day to m/s*/
    4407                         //IssmDouble C = (min(max(Hc,80.),100.) - 80.)/20. * 10./(24*3600.); /*Original MICI! convert from m/day to m/s*/
    4408                         movingfrontvx[iv] = -C*dlsf[0]/norm_dlsf;
    4409                         movingfrontvy[iv] = -C*dlsf[1]/norm_dlsf;
     4511
     4512                        /*Front motion = ice speed (v) - calving rate*/
     4513                        movingfrontvx[iv] = v[0] -C*dlsf[0]/norm_dlsf;
     4514                        movingfrontvy[iv] = v[1] -C*dlsf[1]/norm_dlsf;
    44104515                }
    44114516        }
     
    45874692        norm=sqrt(vector[0]*vector[0] + vector[1]*vector[1]);
    45884693
    4589         normal[0]= + vector[1]/norm;
    4590         normal[1]= - vector[0]/norm;
     4694        normal[0]= + vector[1]/(norm+1e-10);
     4695        normal[1]= - vector[0]/(norm+1e-10);
    45914696}
    45924697/*}}}*/
     
    52145319        IssmDouble calvingratex,calvingratey,thickness,Jdet;
    52155320        IssmDouble rho_ice=FindParam(MaterialsRhoIceEnum);
    5216         Input* thickness_input=this->GetInput(ThicknessEnum); _assert_(thickness_input);
    5217         Input* calvingratex_input=NULL;
    5218         Input* calvingratey_input=NULL;
    5219         if(domaintype==Domain2DhorizontalEnum){
    5220                 calvingratex_input=this->GetInput(CalvingratexEnum); _assert_(calvingratex_input);
    5221                 calvingratey_input=this->GetInput(CalvingrateyEnum); _assert_(calvingratey_input);
    5222         }
    5223         else{
    5224                 calvingratex_input=this->GetInput(CalvingratexAverageEnum); _assert_(calvingratex_input);
    5225                 calvingratey_input=this->GetInput(CalvingrateyAverageEnum); _assert_(calvingratey_input);
    5226         }
     5321        Input* thickness_input    = this->GetInput(ThicknessEnum); _assert_(thickness_input);
     5322        Input* calvingratex_input = this->GetInput(CalvingratexEnum); _assert_(calvingratex_input);
     5323        Input* calvingratey_input = this->GetInput(CalvingrateyEnum); _assert_(calvingratey_input);
    52275324
    52285325        /*Start looping on Gaussian points*/
     
    53405437        /*Get inputs*/
    53415438        IssmDouble flux = 0.;
    5342         IssmDouble calvingratex,calvingratey,vx,vy,vel,meltingrate,meltingratex,meltingratey,thickness,Jdet;
     5439        IssmDouble calvingratex,calvingratey,vx,vy,vel,meltingrate,meltingratex,meltingratey,thickness,Jdet,groundedice;
    53435440        IssmDouble rho_ice=FindParam(MaterialsRhoIceEnum);
    5344         Input* thickness_input=this->GetInput(ThicknessEnum); _assert_(thickness_input);
    5345         Input* calvingratex_input=NULL;
    5346         Input* calvingratey_input=NULL;
    5347         Input* vx_input=NULL;
    5348         Input* vy_input=NULL;
    5349         Input* meltingrate_input=NULL;
    5350         if(domaintype==Domain2DhorizontalEnum){
    5351                 calvingratex_input=this->GetInput(CalvingratexEnum); _assert_(calvingratex_input);
    5352                 calvingratey_input=this->GetInput(CalvingrateyEnum); _assert_(calvingratey_input);
    5353                 vx_input=this->GetInput(VxEnum); _assert_(vx_input);
    5354                 vy_input=this->GetInput(VyEnum); _assert_(vy_input);
    5355                 meltingrate_input=this->GetInput(CalvingMeltingrateEnum); _assert_(meltingrate_input);
    5356         }
    5357         else{
    5358                 calvingratex_input=this->GetInput(CalvingratexAverageEnum); _assert_(calvingratex_input);
    5359                 calvingratey_input=this->GetInput(CalvingrateyAverageEnum); _assert_(calvingratey_input);
    5360         }
     5441        Input* thickness_input    = this->GetInput(ThicknessEnum); _assert_(thickness_input);
     5442        Input *gr_input           = this->GetInput(MaskOceanLevelsetEnum); _assert_(gr_input);
     5443        Input* calvingratex_input = this->GetInput(CalvingratexEnum); _assert_(calvingratex_input);
     5444        Input* calvingratey_input = this->GetInput(CalvingrateyEnum); _assert_(calvingratey_input);
     5445        Input* vx_input           = this->GetInput(VxEnum); _assert_(vx_input);
     5446        Input* vy_input           = this->GetInput(VyEnum); _assert_(vy_input);
     5447        Input* meltingrate_input  = this->GetInput(CalvingMeltingrateEnum); _assert_(meltingrate_input);
    53615448
    53625449        /*Start looping on Gaussian points*/
     
    53665453                calvingratex_input->GetInputValue(&calvingratex,gauss);
    53675454                calvingratey_input->GetInputValue(&calvingratey,gauss);
     5455                gr_input->GetInputValue(&groundedice,gauss);
    53685456                vx_input->GetInputValue(&vx,gauss);
    53695457                vy_input->GetInputValue(&vy,gauss);
    53705458                vel=vx*vx+vy*vy;
    53715459                meltingrate_input->GetInputValue(&meltingrate,gauss);
     5460                if(groundedice<0) meltingrate = 0.;
    53725461                meltingratex=meltingrate*vx/(sqrt(vel)+1.e-14);
    53735462                meltingratey=meltingrate*vy/(sqrt(vel)+1.e-14);
     
    62376326        IssmDouble area,planetarea,planetradius;
    62386327        IssmDouble constant,ratioe;
    6239         IssmDouble I;  //change in ice thickness or water level(Farrel and Clarke, Equ. 4)
    62406328        IssmDouble rho_earth;
    62416329        IssmDouble NewtonG;
    6242         IssmDouble g;
     6330        IssmDouble g, cent_scaling;
    62436331        IssmDouble lati,longi;
    62446332        IssmDouble latitude[NUMVERTICES];
     
    62916379
    62926380        /*Rotational:*/
     6381        #ifdef _HAVE_RESTRICT_
     6382        IssmDouble* __restrict__ tide_love_h  = NULL;
     6383        IssmDouble* __restrict__ tide_love_k  = NULL;
     6384        IssmDouble* __restrict__ tide_love_l  = NULL;
     6385        IssmDouble* __restrict__ LoveRotRSL   = NULL;
     6386        IssmDouble* __restrict__ LoveRotU     = NULL;
     6387        IssmDouble* __restrict__ LoveRothoriz = NULL;
     6388        IssmDouble* __restrict__  Grot        = NULL;
     6389        IssmDouble* __restrict__ GUrot        = NULL;
     6390        IssmDouble* __restrict__ GNrot        = NULL;
     6391        IssmDouble* __restrict__ GErot        = NULL;
     6392        #else
    62936393        IssmDouble* tide_love_h  = NULL;
    62946394        IssmDouble* tide_love_k  = NULL;
    62956395        IssmDouble* tide_love_l  = NULL;
     6396        IssmDouble* LoveRotRSL   = NULL;
     6397        IssmDouble* LoveRotU     = NULL;
     6398        IssmDouble* LoveRothoriz = NULL;
     6399        IssmDouble*  Grot        = NULL;
     6400        IssmDouble* GUrot        = NULL;
     6401        IssmDouble* GNrot        = NULL;
     6402        IssmDouble* GErot        = NULL;
     6403        #endif
     6404
    62966405        IssmDouble  moi_e, moi_p, omega;
    6297         IssmDouble  Grotm1[3],GUrotm1[3],GNrotm1[3],GErotm1[3];
    6298         IssmDouble  Grotm2[3],GUrotm2[3],GNrotm2[3],GErotm2[3];
    6299         IssmDouble  Grotm3[3],GUrotm3[3],GNrotm3[3],GErotm3[3];
    63006406        IssmDouble  Y21cos     , Y21sin     , Y20;
    63016407        IssmDouble dY21cos_dlat,dY21sin_dlat,dY20_dlat;
    63026408        IssmDouble dY21cos_dlon,dY21sin_dlon;
    6303         IssmDouble LoveRotRSL,LoveRotU,LoveRothoriz;
    63046409        IssmDouble polenudge;
    63056410        /*}}}*/
     
    63246429
    63256430        if(computerotation){
    6326                 parameters->FindParam(&tide_love_h,NULL,NULL,TidalLoveHEnum);
    6327                 parameters->FindParam(&tide_love_k,NULL,NULL,TidalLoveKEnum);
    6328                 parameters->FindParam(&tide_love_l,NULL,NULL,TidalLoveLEnum);
    63296431                parameters->FindParam(&moi_e,RotationalEquatorialMoiEnum);
    63306432                parameters->FindParam(&moi_p,RotationalPolarMoiEnum);
    63316433                parameters->FindParam(&omega,RotationalAngularVelocityEnum);
     6434                //parameters->FindParam(&tide_love_h,NULL,NULL,SealevelchangeTidalH2Enum);
     6435                //parameters->FindParam(&tide_love_k,NULL,NULL,SealevelchangeTidalK2Enum);
     6436                //if(horiz) parameters->FindParam(&tide_love_l,NULL,NULL,SealevelchangeTidalL2Enum);
    63326437        }
    63336438        /*}}}*/
     
    63476452                        parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeHViscoElasticEnum)); _assert_(parameter);
    63486453                        parameter->GetParameterValueByPointer((IssmDouble**)&H_viscoelastic_precomputed,NULL);
     6454                }
     6455
     6456                if(computerotation){
     6457                        parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeTidalH2Enum)); _assert_(parameter);
     6458                        parameter->GetParameterValueByPointer((IssmDouble**)&tide_love_h,NULL);
     6459
     6460                        parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeTidalK2Enum)); _assert_(parameter);
     6461                        parameter->GetParameterValueByPointer((IssmDouble**)&tide_love_k,NULL);
     6462
     6463                        if (horiz) {
     6464                                parameter = static_cast<DoubleVecParam*>(this->parameters->FindParamObject(SealevelchangeTidalL2Enum)); _assert_(parameter);
     6465                                parameter->GetParameterValueByPointer((IssmDouble**)&tide_love_l,NULL);
     6466                        }
    63496467                }
    63506468        }
     
    63876505                        IssmDouble alpha;
    63886506                        IssmDouble delPhi,delLambda;
    6389                         /*recover info for this element and vertex:*/
     6507                        /*recovers info for this element and vertex:*/
    63906508                        IssmDouble late= asin(zze[e]/sqrt( pow(xxe[e],2.0)+ pow(yye[e],2.0)+ pow(zze[e],2.0)));
    63916509                        IssmDouble longe= atan2(yye[e],xxe[e]);
     
    63946512                        longi=longitude[i];
    63956513
    6396                         /*Compute alpha angle between centroid and current vertex and index into precomputed tables: */
     6514                        /*Computes alpha angle between centroid and current vertex, and indexes alpha in precomputed tables: */
    63976515                        delPhi=fabs(lati-late); delLambda=fabs(longi-longe); if (delLambda>M_PI)delLambda=2*M_PI-delLambda;
    63986516                        alpha=2.*asin(sqrt(pow(sin(delPhi/2),2)+cos(lati)*cos(late)*pow(sin(delLambda/2),2)));
     
    64626580        /*Compute rotation kernel:{{{*/
    64636581        if(computerotation){
     6582                //initialization
     6583                LoveRotRSL  = xNewZeroInit<IssmDouble>(nt);
     6584                LoveRotU    = xNewZeroInit<IssmDouble>(nt);
     6585                LoveRothoriz= xNewZeroInit<IssmDouble>(nt);
     6586                Grot        = xNewZeroInit<IssmDouble>(3*3*nt); //3 polar motion components * 3 vertices * number of time steps
     6587                GUrot       = xNewZeroInit<IssmDouble>(3*3*nt);
     6588
     6589                if (horiz){
     6590                        GErot=xNewZeroInit<IssmDouble>(3*3*nt);
     6591                        GNrot=xNewZeroInit<IssmDouble>(3*3*nt);
     6592                }
    64646593
    64656594                /*What is the gravity at planet's surface: */
    64666595                g=4.0/3.0*M_PI*rho_earth*NewtonG*planetradius;
    6467 
    6468                 //Amplitude of the rotational feedback
    6469                 LoveRotRSL=((1.0+tide_love_k[2]-tide_love_h[2])/g)*pow(omega*planetradius,2.0);
    6470                 LoveRotU=(tide_love_h[2]/g)*pow(omega*planetradius,2.0);
    6471                 LoveRothoriz=(tide_love_l[2]/g)*pow(omega*planetradius,2.0);
    6472 
     6596                cent_scaling=pow(omega*planetradius,2.0); //centrifugal potential dimensioning constant
     6597                for(int t=0;t<nt;t++){
     6598                        //Amplitude of the rotational feedback
     6599                        //to speed up calculation we include the dimension constant r^2*Omega^2/g, so all 3 of these are in meters
     6600                        LoveRotRSL[t]=((1.0+tide_love_k[t]-tide_love_h[t])/g)*cent_scaling;
     6601                        LoveRotU[t]=(tide_love_h[t]/g)*cent_scaling;
     6602                        if (horiz) LoveRothoriz[t]=(tide_love_l[t]/g)*cent_scaling;
     6603                }
    64736604                for(int i=0;i<3;i++){
    64746605
     
    64896620                        longi=longitude[i];
    64906621
    6491                         //Spherical harmonic functions of degree 2
     6622                        //Spherical harmonic functions of degree 2 (spatial pattern of rotation)
    64926623                        Y21cos= -0.5*sin(2.*lati)*cos(longi);
    64936624                        Y21sin= -0.5*sin(2.*lati)*sin(longi);
    64946625                        Y20   = -(1.0/6.0 - 0.5*cos(2.0*lati));
    64956626
    6496                         Grotm1[i]= LoveRotRSL*Y21cos;
    6497                         Grotm2[i]= LoveRotRSL*Y21sin;
    6498                         Grotm3[i]= LoveRotRSL*Y20;
    6499 
    6500                         if (computeelastic){
    6501                                 GUrotm1[i]= LoveRotU*Y21cos;
    6502                                 GUrotm2[i]= LoveRotU*Y21sin;
    6503                                 GUrotm3[i]= LoveRotU*Y20;
    6504                                 if (horiz){
     6627                        if (computeelastic && horiz){
    65056628                                //bed_N = Love_l * d(Y)/dlat ;
    65066629                                dY21cos_dlat=-cos(2.*lati)*cos(longi);
    65076630                                dY21sin_dlat=-cos(2.*lati)*sin(longi);
    65086631                                dY20_dlat=   -sin(2.*lati);
    6509                                 GNrotm1[i]= LoveRothoriz*dY21cos_dlat;
    6510                                 GNrotm2[i]= LoveRothoriz*dY21sin_dlat;
    6511                                 GNrotm3[i]= LoveRothoriz*dY20_dlat;
    65126632
    65136633                                //bed_E = Love_l * 1/cos(lat) * d(Y)/dlon ;
     
    65156635                                dY21sin_dlon=Y21cos/cos(lati);
    65166636                                //dY20_dlon=0.;
    6517 
    6518                                 GErotm1[i]= LoveRothoriz*dY21cos_dlon;
    6519                                 GErotm2[i]= LoveRothoriz*dY21sin_dlon;
    6520                                 GErotm3[i]= 0.0;
     6637                        }
     6638
     6639                        for(int t=0;t<nt;t++){
     6640
     6641                                Grot[0*3*nt+i*nt+t]= LoveRotRSL[t]*Y21cos; //x component of polar motion
     6642                                Grot[1*3*nt+i*nt+t]= LoveRotRSL[t]*Y21sin; //y
     6643                                Grot[2*3*nt+i*nt+t]= LoveRotRSL[t]*Y20;    //z
     6644
     6645                                if (computeelastic){
     6646                                        GUrot[0*3*nt+i*nt+t]= LoveRotU[t]*Y21cos;
     6647                                        GUrot[1*3*nt+i*nt+t]= LoveRotU[t]*Y21sin;
     6648                                        GUrot[2*3*nt+i*nt+t]= LoveRotU[t]*Y20;
     6649                                        if (horiz){
     6650                                                //bed_N = Love_l * d(Y)/dlat ;
     6651                                                GNrot[0*3*nt+i*nt+t]= LoveRothoriz[t]*dY21cos_dlat;
     6652                                                GNrot[1*3*nt+i*nt+t]= LoveRothoriz[t]*dY21sin_dlat;
     6653                                                GNrot[2*3*nt+i*nt+t]= LoveRothoriz[t]*dY20_dlat;
     6654
     6655                                                //bed_E = Love_l * 1/cos(lat) * d(Y)/dlon ;
     6656                                                GErot[0*3*nt+i*nt+t]= LoveRothoriz[t]*dY21cos_dlon;
     6657                                                GErot[1*3*nt+i*nt+t]= LoveRothoriz[t]*dY21sin_dlon;
     6658                                                GErot[2*3*nt+i*nt+t]= 0.0;
     6659                                        }
    65216660                                }
    65226661                        }
    65236662                }
    6524                 this->AddInput(SealevelGrotm1Enum,&Grotm1[0],P1Enum);
    6525                 this->AddInput(SealevelGrotm2Enum,&Grotm2[0],P1Enum);
    6526                 this->AddInput(SealevelGrotm3Enum,&Grotm3[0],P1Enum);
     6663                this->inputs->SetArrayInput(SealevelchangeGrotEnum,this->lid,Grot,3*3*nt);
    65276664                if (computeelastic){
    6528                         this->AddInput(SealevelGUrotm1Enum,&GUrotm1[0],P1Enum);
    6529                         this->AddInput(SealevelGUrotm2Enum,&GUrotm2[0],P1Enum);
    6530                         this->AddInput(SealevelGUrotm3Enum,&GUrotm3[0],P1Enum);
     6665                        this->inputs->SetArrayInput(SealevelchangeGUrotEnum,this->lid,GUrot,3*3*nt);
    65316666                        if(horiz){
    6532                                 this->AddInput(SealevelGNrotm1Enum,&GNrotm1[0],P1Enum);
    6533                                 this->AddInput(SealevelGNrotm2Enum,&GNrotm2[0],P1Enum);
    6534                                 this->AddInput(SealevelGNrotm3Enum,&GNrotm3[0],P1Enum);
    6535                                 this->AddInput(SealevelGErotm1Enum,&GErotm1[0],P1Enum);
    6536                                 this->AddInput(SealevelGErotm2Enum,&GErotm2[0],P1Enum);
    6537                                 this->AddInput(SealevelGErotm3Enum,&GErotm3[0],P1Enum);
     6667                                this->inputs->SetArrayInput(SealevelchangeGNrotEnum,this->lid,GNrot,3*3*nt);
     6668                                this->inputs->SetArrayInput(SealevelchangeGErotEnum,this->lid,GErot,3*3*nt);
    65386669                        }
    65396670                }
     
    65516682                        viscousN=xNewZeroInit<IssmDouble>(3*nt);
    65526683                        viscousE=xNewZeroInit<IssmDouble>(3*nt);
    6553                         this->inputs->SetArrayInput(SealevelchangeViscousNEnum,this->lid,viscousRSL,3*nt);
    6554                         this->inputs->SetArrayInput(SealevelchangeViscousEEnum,this->lid,viscousU,3*nt);
     6684                        this->inputs->SetArrayInput(SealevelchangeViscousNEnum,this->lid,viscousN,3*nt);
     6685                        this->inputs->SetArrayInput(SealevelchangeViscousEEnum,this->lid,viscousE,3*nt);
    65556686                }
    65566687        }
     
    65666697                        delete GE;
    65676698                }
     6699                if(computerotation){
     6700                        delete Grot;
     6701                        delete GUrot;
     6702                        if (horiz){
     6703                                delete GNrot;
     6704                                delete GErot;
     6705                        }
     6706                }
    65686707        }
    65696708        #else
     
    65746713                        xDelete(GN);
    65756714                        xDelete(GE);
     6715                }
     6716                if(computerotation){
     6717                        xDelete(Grot);
     6718                        xDelete(GUrot);
     6719                        if (horiz){
     6720                                xDelete(GNrot);
     6721                                xDelete(GErot);
     6722                        }
    65766723                }
    65776724        }
     
    71277274}
    71287275/*}}}*/
    7129 void       Tria::SealevelchangeUpdateViscousFields(){ /*{{{*/
     7276void       Tria::SealevelchangeUpdateViscousFields(IssmDouble lincoeff, int newindex, int offset){ /*{{{*/
    71307277
    71317278        /*Inputs:*/
     
    71347281        IssmDouble* viscousN=NULL;
    71357282        IssmDouble* viscousE=NULL;
    7136         IssmDouble* viscoustimes=NULL;
    71377283        int         viscousnumsteps;
    7138         int         viscousindex=0;
    7139         int         newindex=0;
    71407284        int         dummy;
    71417285        bool        viscous=false;
    7142         IssmDouble  currenttime;
    7143         IssmDouble  lincoeff=0;
    7144         int horiz;
     7286        int         horiz=0;
    71457287
    71467288        this->parameters->FindParam(&viscous,SolidearthSettingsViscousEnum);
     
    71487290        if(viscous){
    71497291                this->parameters->FindParam(&horiz,SolidearthSettingsHorizEnum);
    7150 
    71517292                this->parameters->FindParam(&viscousnumsteps,SealevelchangeViscousNumStepsEnum);
    7152                 this->parameters->FindParam(&viscoustimes,NULL,SealevelchangeViscousTimesEnum);
    7153                 this->parameters->FindParam(&viscousindex,SealevelchangeViscousIndexEnum);
    7154                 this->parameters->FindParam(&currenttime,TimeEnum);
    71557293
    71567294                this->inputs->GetArrayPtr(SealevelchangeViscousRSLEnum,this->lid,&viscousRSL,&dummy);
     
    71617299                }
    71627300
    7163                 bool foundtime=false;
    7164                 int offset=1;
    7165                 lincoeff=0;
    7166                 newindex=viscousnumsteps-2;
    7167 
    7168                 for(int t=viscousindex;t<viscousnumsteps;t++){
    7169                         if (viscoustimes[t]>currenttime){
    7170                                 newindex=t-1;
    7171                                 lincoeff=(currenttime-viscoustimes[newindex])/(viscoustimes[t]-viscoustimes[newindex]);
    7172                                 foundtime=true;
    7173                                 offset=0;
    7174                                 break;
    7175                         }
    7176                 }
    7177 
    7178                 if(!foundtime) lincoeff=1;
    7179                 viscoustimes[newindex]=currenttime;
    71807301                for(int i=0;i<NUMVERTICES;i++){
    71817302                        viscousRSL[i*viscousnumsteps+newindex+offset]=(1-lincoeff)*viscousRSL[i*viscousnumsteps+newindex]+lincoeff*viscousRSL[i*viscousnumsteps+newindex+1];
     
    71867307                        }
    71877308                }
    7188                 viscousindex=newindex+offset;
    7189 
    7190                 this->parameters->SetParam(viscousindex,SealevelchangeViscousIndexEnum);
    7191                 this->parameters->SetParam(viscoustimes,viscousnumsteps,SealevelchangeViscousTimesEnum);
    7192 
    7193                 /*free allocations:*/
    7194                 xDelete<IssmDouble>(viscoustimes);
     7309
    71957310        }
    71967311
     
    71987313/*}}}*/
    71997314void       Tria::SealevelchangeBarystaticLoads(GrdLoads* loads,  BarystaticContributions* barycontrib, SealevelGeometry* slgeom){ /*{{{*/
     7315
     7316        int nel;
    72007317
    72017318        /*Inputs:*/
     
    72037320        IssmDouble W[NUMVERTICES];
    72047321        IssmDouble BP[NUMVERTICES];
     7322        IssmDouble* areae=NULL;
    72057323
    72067324        /*output: */
     
    72197337        this->parameters->FindParam(&rho_water,MaterialsRhoSeawaterEnum);
    72207338        this->parameters->FindParam(&rho_freshwater,MaterialsRhoFreshwaterEnum);
     7339        this->parameters->FindParam(&areae,&nel,AreaeEnum);
    72217340
    72227341        /*Retrieve inputs:*/
     
    72437362
    72447363        /*Compute barystatic component in kg:*/
     7364        // Note: Iavg, etc, already include partial area factor phi for subelement loading
    72457365        bslcice =   -slgeom->LoadArea[SLGEOM_ICE][this->lid]*Iavg;
    72467366        bslchydro = -slgeom->LoadArea[SLGEOM_WATER][this->lid]*Wavg;
     
    72677387                BPavg=0;
    72687388        }
    7269         /*Plug remaining values into centroi load vector:*/
     7389        /*Plug remaining values into centroid load vector:*/
    72707390        loads->vloads->SetValue(this->sid,Iavg+Wavg+BPavg,INS_VAL);
    72717391
     
    72797399        /*sal green function:*/
    72807400        IssmDouble* G=NULL;
     7401        IssmDouble* Grot=NULL;
    72817402        IssmDouble* Gsub[SLGEOM_NUMLOADS];
    72827403        bool computefuture=false;
     
    72887409        int  size;
    72897410        int  nel,nbar;
    7290         IssmDouble Grotm1[3];
    7291         IssmDouble Grotm2[3];
    7292         IssmDouble Grotm3[3];
     7411
    72937412
    72947413        this->parameters->FindParam(&sal,SolidearthSettingsSelfAttractionEnum);
     
    73027421                this->inputs->GetArrayPtr(SealevelchangeGsubelHydroEnum,this->lid,&Gsub[SLGEOM_WATER],&size);
    73037422                this->inputs->GetArrayPtr(SealevelchangeGsubelOceanEnum,this->lid,&Gsub[SLGEOM_OCEAN],&size);
    7304 
    7305                 this->SealevelchangeGxL(sealevelpercpu, G, Gsub, loads, slgeom, nel,percpu=true,SealevelchangeViscousRSLEnum,computefuture=false);
    7306         }
    7307 
    7308         if(rotation){
    7309                 Element::GetInputListOnVertices(&Grotm1[0],SealevelGrotm1Enum);
    7310                 Element::GetInputListOnVertices(&Grotm2[0],SealevelGrotm2Enum);
    7311                 Element::GetInputListOnVertices(&Grotm3[0],SealevelGrotm3Enum);
    7312 
    7313                 for(int i=0;i<NUMVERTICES;i++){
    7314                         if(slgeom->lids[this->vertices[i]->lid]==this->lid){
    7315                                 sealevelpercpu[this->vertices[i]->lid]+=Grotm1[i]*polarmotionvector[0]+Grotm2[i]*polarmotionvector[1]+Grotm3[i]*polarmotionvector[2];
    7316                         }
    7317                 }
    7318         }
     7423                if (rotation)   this->inputs->GetArrayPtr(SealevelchangeGrotEnum,this->lid,&Grot,&size);
     7424
     7425                this->SealevelchangeGxL(sealevelpercpu, G, Gsub, Grot, loads, polarmotionvector, slgeom, nel,percpu=true,SealevelchangeViscousRSLEnum,computefuture=false);
     7426        }
     7427
    73197428        return;
    73207429} /*}}}*/
    73217430void       Tria::SealevelchangeOceanAverage(GrdLoads* loads, Vector<IssmDouble>* oceanareas, Vector<IssmDouble>* subelementoceanareas, IssmDouble* sealevelpercpu, SealevelGeometry* slgeom){ /*{{{*/
    73227431
    7323         /*sal green function:*/
    73247432        IssmDouble oceanaverage=0;
    73257433        IssmDouble oceanarea=0;
     
    73697477        IssmDouble* GE=NULL;
    73707478        IssmDouble* GN=NULL;
     7479        IssmDouble* Grot=NULL;
     7480        IssmDouble* GUrot=NULL;
     7481        IssmDouble* GNrot=NULL;
     7482        IssmDouble* GErot=NULL;
    73717483        IssmDouble* Gsub[SLGEOM_NUMLOADS];
    73727484        IssmDouble* GUsub[SLGEOM_NUMLOADS];
     
    73777489        int horiz;
    73787490        int size;
    7379         IssmDouble Grotm1[3];
    7380         IssmDouble Grotm2[3];
    7381         IssmDouble Grotm3[3];
    7382         IssmDouble GUrotm1[3];
    7383         IssmDouble GUrotm2[3];
    7384         IssmDouble GUrotm3[3];
    7385         IssmDouble GNrotm1[3];
    7386         IssmDouble GNrotm2[3];
    7387         IssmDouble GNrotm3[3];
    7388         IssmDouble GErotm1[3];
    7389         IssmDouble GErotm2[3];
    7390         IssmDouble GErotm3[3];
     7491
    73917492        bool rotation= false;
    73927493        bool elastic=false;
     
    74247525                                this->inputs->GetArrayPtr(SealevelchangeGEsubelOceanEnum,this->lid,&GEsub[SLGEOM_OCEAN],&size);
    74257526                        }
    7426                 }
    7427                 this->SealevelchangeGxL(&RSLGrd[0],G, Gsub, loads, slgeom, nel,percpu=false,SealevelchangeViscousRSLEnum,computefuture=true);
     7527                        if (rotation) {
     7528                                this->inputs->GetArrayPtr(SealevelchangeGrotEnum,this->lid,&Grot,&size);
     7529                                this->inputs->GetArrayPtr(SealevelchangeGUrotEnum,this->lid,&GUrot,&size);
     7530                                if (horiz){
     7531                                        this->inputs->GetArrayPtr(SealevelchangeGErotEnum,this->lid,&GErot,&size);
     7532                                        this->inputs->GetArrayPtr(SealevelchangeGNrotEnum,this->lid,&GNrot,&size);
     7533                                }
     7534                        }
     7535                }
     7536                this->SealevelchangeGxL(&RSLGrd[0],G, Gsub, Grot, loads, polarmotionvector, slgeom, nel,percpu=false,SealevelchangeViscousRSLEnum,computefuture=true);
    74287537
    74297538                if(elastic){
    7430                         this->SealevelchangeGxL(&UGrd[0],GU, GUsub, loads, slgeom, nel,percpu=false,SealevelchangeViscousUEnum,computefuture=true);
    7431                         if(horiz ){
    7432                                 this->SealevelchangeGxL(&NGrd[0],GN, GNsub, loads, slgeom, nel,percpu=false,SealevelchangeViscousNEnum,computefuture=true);
    7433                                 this->SealevelchangeGxL(&EGrd[0],GE, GEsub, loads, slgeom, nel,percpu=false,SealevelchangeViscousEEnum,computefuture=true);
    7434                         }
    7435                 }
    7436         }
    7437 
    7438         if(rotation){
    7439                 Element::GetInputListOnVertices(&Grotm1[0],SealevelGrotm1Enum);
    7440                 Element::GetInputListOnVertices(&Grotm2[0],SealevelGrotm2Enum);
    7441                 Element::GetInputListOnVertices(&Grotm3[0],SealevelGrotm3Enum);
    7442 
    7443                 for(int i=0;i<NUMVERTICES;i++){
    7444                         if(slgeom->lids[this->vertices[i]->lid]==this->lid){
    7445                                 RSLGrd[i]+=Grotm1[i]*polarmotionvector[0]+Grotm2[i]*polarmotionvector[1]+Grotm3[i]*polarmotionvector[2];
    7446                         }
    7447                 }
    7448 
    7449                 if (elastic){
    7450                         Element::GetInputListOnVertices(&GUrotm1[0],SealevelGUrotm1Enum);
    7451                         Element::GetInputListOnVertices(&GUrotm2[0],SealevelGUrotm2Enum);
    7452                         Element::GetInputListOnVertices(&GUrotm3[0],SealevelGUrotm3Enum);
    7453 
    7454                         for(int i=0;i<NUMVERTICES;i++){
    7455                                 if(slgeom->lids[this->vertices[i]->lid]==this->lid){
    7456                                         UGrd[i]+=GUrotm1[i]*polarmotionvector[0]+GUrotm2[i]*polarmotionvector[1]+GUrotm3[i]*polarmotionvector[2];
    7457                                 }
    7458                         }
    7459                         if (horiz){
    7460                                 Element::GetInputListOnVertices(&GNrotm1[0],SealevelGNrotm1Enum);
    7461                                 Element::GetInputListOnVertices(&GNrotm2[0],SealevelGNrotm2Enum);
    7462                                 Element::GetInputListOnVertices(&GNrotm3[0],SealevelGNrotm3Enum);
    7463                                 Element::GetInputListOnVertices(&GErotm1[0],SealevelGErotm1Enum);
    7464                                 Element::GetInputListOnVertices(&GErotm2[0],SealevelGErotm2Enum);
    7465                                 Element::GetInputListOnVertices(&GErotm3[0],SealevelGErotm3Enum);
    7466 
    7467                                 for(int i=0;i<NUMVERTICES;i++){
    7468                                         if(slgeom->lids[this->vertices[i]->lid]==this->lid){
    7469                                                 NGrd[i]+=GNrotm1[i]*polarmotionvector[0]+GNrotm2[i]*polarmotionvector[1]+GNrotm3[i]*polarmotionvector[2];
    7470                                                 EGrd[i]+=GErotm1[i]*polarmotionvector[0]+GErotm2[i]*polarmotionvector[1]+GErotm3[i]*polarmotionvector[2];
    7471                                         }
    7472                                 }
     7539                        this->SealevelchangeGxL(&UGrd[0],GU, GUsub, GUrot, loads, polarmotionvector, slgeom, nel,percpu=false,SealevelchangeViscousUEnum,computefuture=true);
     7540                        if(horiz){
     7541                                this->SealevelchangeGxL(&NGrd[0],GN, GNsub, GNrot, loads, polarmotionvector, slgeom, nel,percpu=false,SealevelchangeViscousNEnum,computefuture=true);
     7542                                this->SealevelchangeGxL(&EGrd[0],GE, GEsub, GErot, loads, polarmotionvector, slgeom, nel,percpu=false,SealevelchangeViscousEEnum,computefuture=true);
    74737543                        }
    74747544                }
     
    74957565
    74967566} /*}}}*/
    7497 void       Tria::SealevelchangeGxL(IssmDouble* grdfieldout, IssmDouble* G, IssmDouble** Gsub, GrdLoads* loads, SealevelGeometry* slgeom, int nel, bool percpu, int viscousenum, bool computefuture) { /*{{{*/
     7567void       Tria::SealevelchangeGxL(IssmDouble* grdfieldout, IssmDouble* G, IssmDouble** Gsub, IssmDouble* Grot, GrdLoads* loads, IssmDouble* polarmotionvector, SealevelGeometry* slgeom, int nel, bool percpu, int viscousenum, bool computefuture) { /*{{{*/
     7568
     7569        //This function performs the actual convolution between Green functions and surface Loads for a particular grd field
    74987570
    74997571        IssmDouble* grdfield=NULL;
    75007572        int i,e,l,t,nbar;
    75017573        bool computeviscous=false;
     7574        bool rotation=false;
    75027575        IssmDouble* viscousfield=NULL;
    7503         int nt=1; //important
     7576        int nt=1; //important, ensures there is a defined value if computeviscous is false
    75047577        int viscousindex=0; //important
    75057578        int viscousnumsteps=1; //important
    75067579
    75077580        this->parameters->FindParam(&computeviscous,SolidearthSettingsViscousEnum);
     7581        this->parameters->FindParam(&rotation,SolidearthSettingsRotationEnum);
    75087582        if(computeviscous){
    75097583                this->parameters->FindParam(&viscousnumsteps,SealevelchangeViscousNumStepsEnum);
    7510                 if(computefuture) nt=viscousnumsteps;
     7584                this->parameters->FindParam(&viscousindex,SealevelchangeViscousIndexEnum);
     7585                if(computefuture) {
     7586                        nt=viscousnumsteps-viscousindex+2; //number of time steps remaining to reach final_time, +1 is sufficient with no adaptative time stepping, +2 necessary otherwise; we assume the safe choice here for the sake of simplicity
     7587                        if (nt>viscousnumsteps) nt=viscousnumsteps;
     7588                }
    75117589                else nt=1;
    7512 
    7513                 //allocate
    7514                 grdfield=xNewZeroInit<IssmDouble>(3*nt);
    7515         }
    7516         else grdfield=xNewZeroInit<IssmDouble>(3*nt);
    7517 
    7518         if(loads->sealevelloads){
    7519 
     7590        }
     7591        //allocate
     7592        grdfield=xNewZeroInit<IssmDouble>(3*nt);
     7593
     7594        if(rotation){ //add rotational feedback
     7595                for(int i=0;i<NUMVERTICES;i++){ //vertices
     7596                        if(slgeom->lids[this->vertices[i]->lid]==this->lid){
     7597                                for (int m=0;m<3;m++){ //polar motion components
     7598                                        for(t=0;t<nt;t++){ //time
     7599                                                int index=m*3*viscousnumsteps+i*viscousnumsteps+t;
     7600                                                grdfield[i*nt+t]+=Grot[index]*polarmotionvector[m];
     7601                                        }
     7602                                }
     7603                        }
     7604                }
     7605        }
     7606
     7607
     7608        if(loads->sealevelloads){ // general case: loads + sealevel loads
    75207609                for(i=0;i<NUMVERTICES;i++) {
    75217610                        if(slgeom->lids[this->vertices[i]->lid]!=this->lid)continue;
     
    75467635        }
    75477636        else{  //this is the initial convolution where only loads are provided
    7548 
    75497637                for(i=0;i<NUMVERTICES;i++) {
    75507638                        if(slgeom->lids[this->vertices[i]->lid]!=this->lid)continue;
     
    75677655        }
    75687656
    7569         if(computeviscous){
     7657        if(computeviscous){ /*{{{*/
     7658                // we need to do up to 3 things (* = only if computefuture)
     7659                // 1*: add new grdfield contribution to the viscous stack for future time steps
     7660                // 2: collect viscous grdfield from past loads due at present-day and add it to grdfield[current_time]
     7661                // 3*: subtract from viscous stack the grdfield that has already been accounted for so we don't add it again at the next time step
     7662
    75707663                IssmDouble* grdfieldinterp=NULL;
    75717664                IssmDouble* viscoustimes=NULL;
     
    75747667                IssmDouble  timeacc;
    75757668
    7576                 this->parameters->FindParam(&viscousindex,SealevelchangeViscousIndexEnum);
    75777669                this->parameters->FindParam(&viscoustimes,NULL,SealevelchangeViscousTimesEnum);
    75787670                this->parameters->FindParam(&final_time,TimesteppingFinalTimeEnum);
    75797671                this->parameters->FindParam(&timeacc,SolidearthSettingsTimeAccEnum);
    75807672                this->inputs->GetArrayPtr(viscousenum,this->lid,&viscousfield,NULL);
     7673                /* Map new grdfield generated by present-day loads onto viscous time vector*/
    75817674                if(computefuture){
    7582                         grdfieldinterp=xNew<IssmDouble>(3*nt);
     7675                        grdfieldinterp=xNewZeroInit<IssmDouble>(3*viscousnumsteps);
     7676                        //viscousindex time and first time step of grdfield coincide, so just copy that value
     7677                        for(int i=0;i<NUMVERTICES;i++){
     7678                                if(slgeom->lids[this->vertices[i]->lid]!=this->lid)continue;
     7679                                grdfieldinterp[i*viscousnumsteps+viscousindex]=  grdfield[i*nt+0];
     7680                        }
    75837681                        if(viscoustimes[viscousindex]<final_time){
     7682                                //And interpolate the rest of the points in the future
    75847683                                lincoeff=(viscoustimes[viscousindex+1]-viscoustimes[viscousindex])/timeacc;
    7585                                 for(int t=viscousindex;t<nt;t++){
    7586                                         if(t==viscousindex){
    7587                                                 for(int i=0;i<NUMVERTICES;i++){
    7588                                                         if(slgeom->lids[this->vertices[i]->lid]!=this->lid)continue;
    7589                                                         grdfieldinterp[i*nt+t]=  grdfield[i*nt+0];
    7590                                                 }
    7591                                         }
    7592                                         else{
    7593                                                 for(int i=0;i<NUMVERTICES;i++){
    7594                                                         if(slgeom->lids[this->vertices[i]->lid]!=this->lid)continue;
    7595                                                         grdfieldinterp[i*nt+t]=  (1-lincoeff)*grdfield[i*nt+(t-viscousindex-1)]+lincoeff*grdfield[i*nt+(t-viscousindex)];
    7596                                                 }
     7684                                for(int t=viscousindex+1;t<viscousnumsteps;t++){
     7685                                        for(int i=0;i<NUMVERTICES;i++){
     7686                                                if(slgeom->lids[this->vertices[i]->lid]!=this->lid)continue;
     7687                                                grdfieldinterp[i*viscousnumsteps+t]=  (1-lincoeff)*grdfield[i*nt+(t-viscousindex-1)]+lincoeff*grdfield[i*nt+(t-viscousindex)];
    75977688                                        }
    75987689                                }
     
    76067697                }
    76077698
    7608                 if(computefuture){ /*update viscous stack with future deformation from present load: */
    7609 
    7610                         for(int t=nt-1;t>=viscousindex;t--){
     7699                /*update viscous stack with future deformation from present load: */
     7700                if(computefuture){
     7701                        for(int t=viscousnumsteps-1;t>=viscousindex;t--){
    76117702                                for(int i=0;i<NUMVERTICES;i++){
    76127703                                        if(slgeom->lids[this->vertices[i]->lid]!=this->lid)continue;
    76137704                                        //offset viscousfield to remove all deformation that has already been added
    7614                                         viscousfield[i*viscousnumsteps+t]+=grdfieldinterp[i*nt+t]-grdfieldinterp[i*nt+viscousindex]-viscousfield[i*viscousnumsteps+viscousindex];
     7705                                        viscousfield[i*viscousnumsteps+t]+=grdfieldinterp[i*viscousnumsteps+t]-grdfieldinterp[i*viscousnumsteps+viscousindex]-viscousfield[i*viscousnumsteps+viscousindex];
    76157706                                }
    76167707                        }
    7617                         /*Re-add viscous stack now that we updated:*/
     7708                        /*Save viscous stack now that we updated the values:*/
    76187709                        this->inputs->SetArrayInput(viscousenum,this->lid,viscousfield,3*viscousnumsteps);
    76197710                }
     
    76217712                /*Free allocatoins:*/
    76227713                xDelete<IssmDouble>(viscoustimes);
    7623         }
     7714        }
     7715        /*}}}*/
    76247716
    76257717        /*store values computed on vertices, but don't repeat the computation if another element already computed it!:*/
     
    76367728
    76377729} /*}}}*/
    7638 void       Tria::SealevelchangeMomentOfInertiaCentroid(IssmDouble* dI_list, GrdLoads* loads, SealevelGeometry* slgeom){/*{{{*/
    7639 
    7640         IssmDouble S=0;
    7641 
    7642         /*Compute area of element:*/
    7643         IssmDouble area,planetarea,re;
    7644         IssmDouble late,longe;
    7645         this->Element::GetInputValue(&area,AreaEnum);
    7646 
    7647         /*recover parameters: */
    7648         this->parameters->FindParam(&planetarea,SolidearthPlanetAreaEnum);
    7649         this->parameters->FindParam(&re,SolidearthPlanetRadiusEnum);
    7650         late=slgeom->late[this->lid]/180*M_PI;
    7651         longe=slgeom->longe[this->lid]/180*M_PI;
    7652 
    7653         /*recover total load: */
    7654         if(loads->loads) S+=loads->loads[this->Sid()];
    7655         if(loads->sealevelloads) S+=loads->sealevelloads[this->Sid()];
    7656 
    7657         /* Perturbation terms for moment of inertia (moi_list):
    7658          * computed analytically (see Wu & Peltier, eqs 10 & 32)
    7659          * also consistent with my GMD formulation!
    7660          * ALL in geographic coordinates
    7661          * */
    7662         dI_list[0] = -4*M_PI*(S*area)*pow(re,4)*(sin(late)*cos(late)*cos(longe))/planetarea;
    7663         dI_list[1] = -4*M_PI*(S*area)*pow(re,4)*(sin(late)*cos(late)*sin(longe))/planetarea;
    7664         dI_list[2] = +4*M_PI*(S*area)*pow(re,4)*(1-pow(sin(late),2))/planetarea;
    7665         return;
    7666 }/*}}}*/
    7667 void       Tria::SealevelchangeMomentOfInertiaSubElement(IssmDouble* dI_list, GrdLoads* grdloads,  SealevelGeometry* slgeom){/*{{{*/
    7668 
    7669         IssmDouble  SA=0;
    7670         IssmDouble* loads=NULL;
    7671         IssmDouble* sealevelloads=NULL;
    7672         IssmDouble  late,longe,re;
    7673         int         intj;
    7674         IssmDouble  area;
    7675         IssmDouble  planetarea;
    7676 
    7677         /*recover parameters: */
    7678         this->parameters->FindParam(&planetarea,SolidearthPlanetAreaEnum);
    7679         this->parameters->FindParam(&re,SolidearthPlanetRadiusEnum);
    7680 
    7681         /*Initalize:*/
    7682         for(int i=0;i<3;i++)dI_list[i]=0;
    7683 
    7684         /*Go through our loads:*/
    7685         for(int i=0;i<SLGEOM_NUMLOADS;i++){
    7686                 if(slgeom->issubelement[i][this->lid]){
    7687                         loads=grdloads->subloads[i];
    7688                         if(i==SLGEOM_OCEAN) sealevelloads=grdloads->subsealevelloads;
    7689                         intj=slgeom->subelementmapping[i][this->lid];
    7690                         late=slgeom->latbarycentre[i][intj]/180*M_PI;
    7691                         longe=slgeom->longbarycentre[i][intj]/180*M_PI;
    7692                         area=slgeom->area_subel[i][intj];
    7693 
    7694                         /*recover total load: */
    7695                         if(loads) SA+=loads[intj]*area;
    7696                         if(sealevelloads) SA+=sealevelloads[intj]*area;
    7697                 }
    7698         }
    7699 
    7700         /* Perturbation terms for moment of inertia (moi_list):
    7701          * computed analytically (see Wu & Peltier, eqs 10 & 32)
    7702          * also consistent with my GMD formulation!
    7703          * ALL in geographic coordinates
    7704          * */
    7705         dI_list[0] += -4*M_PI*(SA)*pow(re,4)*(sin(late)*cos(late)*cos(longe))/planetarea;
    7706         dI_list[1] += -4*M_PI*(SA)*pow(re,4)*(sin(late)*cos(late)*sin(longe))/planetarea;
    7707         dI_list[2] += +4*M_PI*(SA)*pow(re,4)*(1-pow(sin(late),2))/planetarea;
    7708 
    7709         return;
    7710 }/*}}}*/
     7730
    77117731void       Tria::SealevelchangeShift(GrdLoads* loads,  IssmDouble offset, SealevelGeometry* slgeom){ /*{{{*/
    77127732
  • issm/trunk/src/c/classes/Elements/Tria.h

    r26744 r27035  
    5555                void        AverageOntoPartition(Vector<IssmDouble>* partition_contributions,Vector<IssmDouble>* partition_areas,IssmDouble* vertex_response,IssmDouble* qmu_part);
    5656                void                    CalvingRateVonmises();
     57                void                    CalvingRateTest();
    5758                void        CalvingCrevasseDepth();
    5859                void                    CalvingRateLevermann();
    5960                void                    CalvingFluxLevelset();
    6061                void                    CalvingMeltingFluxLevelset();
     62                void                    CalvingRateParameterization();
    6163                IssmDouble  CharacteristicLength(void);
    6264                void        ComputeBasalStress(void);
     
    6466                void        ComputeEsaStrainAndVorticity();
    6567                void        ComputeSigmaNN();
     68                void        ComputeSigmaVM();
    6669                void        ComputeStressTensor();
    6770                void        ComputeSurfaceNormalVelocity();
     
    177180                void       SealevelchangeDeformationConvolution(IssmDouble* sealevelpercpu, GrdLoads* loads, IssmDouble* rotationvector,SealevelGeometry* slgeom);
    178181                void       SealevelchangeShift(GrdLoads* loads,  IssmDouble offset, SealevelGeometry* slgeom);
    179                 void       SealevelchangeMomentOfInertiaCentroid(IssmDouble* dI_list, GrdLoads* loads,  SealevelGeometry* slgeom);
    180                 void       SealevelchangeMomentOfInertiaSubElement(IssmDouble* dI_list, GrdLoads* loads, SealevelGeometry* slgeom);
    181                 void       SealevelchangeUpdateViscousFields();
     182                void       SealevelchangeUpdateViscousFields(IssmDouble lincoeff, int newindex, int offset);
    182183                #endif
    183184                /*}}}*/
     
    243244                void           UpdateConstraintsExtrudeFromBase(void);
    244245                void           UpdateConstraintsExtrudeFromTop(void);
    245                 void           SealevelchangeGxL(IssmDouble* sealevel, IssmDouble* G, IssmDouble** Gsub, GrdLoads* loads, SealevelGeometry* slgeom, int nel, bool percpu,int stackenum,bool computefuture);
     246                void           SealevelchangeGxL(IssmDouble* sealevel, IssmDouble* G, IssmDouble** Gsub, IssmDouble* Grot, GrdLoads* loads, IssmDouble* polarmotionvector,SealevelGeometry* slgeom, int nel, bool percpu,int stackenum,bool computefuture);
    246247                /*}}}*/
    247248
  • issm/trunk/src/c/classes/ExternalResults/GenericExternalResult.h

    r26744 r27035  
    227227} /*}}}*/
    228228template <> inline void GenericExternalResult<bool>::Marshall(MarshallHandle* marshallhandle){/*{{{*/
    229         printf("-------------- file: GenericExternalResult.h line: %i\n",__LINE__);
    230229        this->GenericMarshall(marshallhandle);
    231230
     
    331330} /*}}}*/
    332331template <> inline void GenericExternalResult<char*>::Marshall(MarshallHandle* marshallhandle){/*{{{*/
    333         printf("-------------- file: GenericExternalResult.h line: %i\n",__LINE__);
    334332        marshallhandle->call(this->id);
    335333        marshallhandle->call(this->result_name);
     
    456454} /*}}}*/
    457455template <> inline void GenericExternalResult<int*>::Marshall(MarshallHandle* marshallhandle){/*{{{*/
    458         printf("-------------- file: GenericExternalResult.h line: %i\n",__LINE__);
    459456
    460457        int object_enum = this->ObjectEnum();
     
    590587} /*}}}*/
    591588template <> inline void GenericExternalResult<IssmPDouble*>::Marshall(MarshallHandle* marshallhandle){/*{{{*/
    592         printf("-------------- file: GenericExternalResult.h line: %i\n",__LINE__);
    593589
    594590        int object_enum = this->ObjectEnum();
  • issm/trunk/src/c/classes/FemModel.cpp

    r26744 r27035  
    576576}
    577577/*}}}*/
    578 void FemModel::Restart(){ /*{{{*/
    579 
    580         FILE* restartfid=NULL;
    581         char* restartfilename = NULL;
    582         int   femmodel_size=0;
    583         int   fread_return=0;
    584         char* femmodel_buffer=NULL;
    585         char* femmodel_buffer_ini=NULL;
     578void FemModel::Restart(int verboselevel){ /*{{{*/
     579
     580        FILE *restartfid          = NULL;
     581        char *restartfilename    = NULL;
     582        int   femmodel_size       = 0;
     583        int   fread_return        = 0;
     584        char *femmodel_buffer     = NULL;
     585        char *femmodel_buffer_ini = NULL;
    586586
    587587        /*First, recover the name of the restart file: */
     
    597597
    598598        /*Print banner*/
    599         _printf0_("                                                                    \n");
    600         _printf0_("====================================================================\n");
    601         _printf0_(" RESTART DETECTED: "<<restartfilename<<                            "\n");
    602         _printf0_("====================================================================\n");
    603         _printf0_("                                                                    \n");
     599   if(verboselevel>1){
     600      _printf0_("                                                                    \n");
     601      _printf0_("====================================================================\n");
     602      _printf0_(" RESTART DETECTED: "<<restartfilename<<                            "\n");
     603      _printf0_("====================================================================\n");
     604      _printf0_("                                                                    \n");
     605   }
     606   else if(verboselevel==1){
     607      _printf0_("    == restarting from "<<restartfilename<<"\n");
     608   }
     609   else{
     610      /*Do not print anything*/
     611   }
    604612
    605613        /*Figure out size of buffer to be read: */
     
    645653
    646654        /*Read files*/
    647         this->Restart();
     655        this->Restart(1);
    648656
    649657        /*Clean up and return*/
     
    30973105void FemModel::UpdateConstraintsx(void){ /*{{{*/
    30983106
    3099         IssmDouble time;
     3107        IssmDouble time,yts;
    31003108        int        analysis_type,config_type;
    31013109
     
    31043112        parameters->FindParam(&config_type,ConfigurationTypeEnum);
    31053113        parameters->FindParam(&time,TimeEnum);
     3114        parameters->FindParam(&yts,ConstantsYtsEnum);
    31063115
    31073116        int index=AnalysisIndex(config_type);
     
    31093118
    31103119        /*start module: */
    3111         if(VerboseModule()) _printf0_("   Updating constraints and active domain of analysis " << EnumToStringx(analysis_type)  << " for time: " << time << "\n");
     3120        if(VerboseModule()) _printf0_("   Updating constraints and active domain of analysis " << EnumToStringx(analysis_type)  << " for time: " << time/yts << "\n");
    31123121
    31133122        Analysis* analysis= EnumToAnalysis(analysis_type);
     
    31213130        NodesDofx(nodes,parameters);
    31223131
    3123 }
    3124 /*}}}*/
     3132}/*}}}*/
    31253133int  FemModel::UpdateVertexPositionsx(void){ /*{{{*/
    31263134
     
    32113219        this->parameters->FindParam(&temp,FlowequationIsSSAEnum); iomodel->AddConstant(new IoConstant(temp,"md.flowequation.isSSA"));
    32123220        this->parameters->FindParam(&temp,FlowequationIsL1L2Enum); iomodel->AddConstant(new IoConstant(temp,"md.flowequation.isL1L2"));
    3213         this->parameters->FindParam(&temp,FlowequationIsMLHOEnum); iomodel->AddConstant(new IoConstant(temp,"md.flowequation.isMLHO"));
     3221        this->parameters->FindParam(&temp,FlowequationIsMOLHOEnum); iomodel->AddConstant(new IoConstant(temp,"md.flowequation.isMOLHO"));
    32143222        this->parameters->FindParam(&temp,FlowequationIsHOEnum); iomodel->AddConstant(new IoConstant(temp,"md.flowequation.isHO"));
    32153223        this->parameters->FindParam(&temp,FlowequationIsFSEnum); iomodel->AddConstant(new IoConstant(temp,"md.flowequation.isFS"));
  • issm/trunk/src/c/classes/FemModel.h

    r26744 r27035  
    8383                void InitFromFids(char* rootpath, FILE* IOMODEL, FILE* toolkitsoptionsfid, int in_solution_type, bool trace, IssmPDouble* X=NULL);
    8484                void Marshall(MarshallHandle* marshallhandle);
    85                 void Restart(void);
     85                void Restart(int verboselevel=2);
    8686                void RestartAD(int step);
    8787                void SetCurrentConfiguration(int configuration_type);
  • issm/trunk/src/c/classes/GrdLoads.cpp

    r26744 r27035  
    6868
    6969} /*}}}*/
     70void GrdLoads::SHDegree2Coefficients(IssmDouble* deg2coeff, FemModel* femmodel, SealevelGeometry* slgeom){
     71
     72        IssmDouble area,re, S;
     73        int ylmindex, intj;
     74        IssmDouble deg2coeff_local[5];
     75
     76        femmodel->parameters->FindParam(&re,SolidearthPlanetRadiusEnum);
     77
     78        for (int c=0;c<5;c++) deg2coeff_local[c]=0;
     79
     80        for(Object* & object : femmodel->elements->objects){
     81                Element* element = xDynamicCast<Element*>(object);
     82                //first, loads on centroids
     83                S=0;
     84                S+=loads[element->Sid()];
     85
     86                if(sealevelloads) S+=sealevelloads[element->Sid()];
     87                if(S!=0){
     88                        element->Element::GetInputValue(&area,AreaEnum);
     89
     90                        for (int c=0;c<5;c++){ //degree l=2 has 2*l+1=5 coefficients: 2,0; 2,1cos; 2,1sin; 2,2cos; 2,2sin
     91                                ylmindex=(4+c)*slgeom->localnel+element->lid; // starting at index=l^2
     92                                deg2coeff_local[c] += S*area/re/re*slgeom->Ylm[ylmindex];
     93                        }
     94                }
     95                //add loads on subelement barycenters
     96                for (int i=0;i<SLGEOM_NUMLOADS;i++){
     97                        if (slgeom->issubelement[i][element->lid]){
     98                                intj=slgeom->subelementmapping[i][element->lid];
     99                                S=0;
     100                                S+=subloads[i][intj];
     101                                if(i==SLGEOM_OCEAN && sealevelloads) S+=subsealevelloads[intj];
     102                                if(S!=0){
     103                                        area=slgeom->area_subel[i][intj];
     104                                        for (int c=0;c<5;c++){ //degree l=2 has 2*l+1=5 coefficients
     105                                                ylmindex=(4+c)*slgeom->localnel+element->lid; // starting at index=l^2
     106                                                deg2coeff_local[c] += S*area/re/re*slgeom->Ylm_subel[i][ylmindex];
     107                                        }
     108                                }
     109                        }
     110                }
     111        }
     112
     113        //sum each degree 2 coefficient across all cpus to get global total
     114        ISSM_MPI_Reduce (&deg2coeff_local[0],&deg2coeff[0],1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
     115        ISSM_MPI_Bcast(&deg2coeff[0],1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
     116        ISSM_MPI_Reduce (&deg2coeff_local[1],&deg2coeff[1],1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
     117        ISSM_MPI_Bcast(&deg2coeff[1],1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
     118        ISSM_MPI_Reduce (&deg2coeff_local[2],&deg2coeff[2],1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
     119        ISSM_MPI_Bcast(&deg2coeff[2],1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
     120
     121}
  • issm/trunk/src/c/classes/GrdLoads.h

    r26744 r27035  
    2929                void BroadcastLoads(void);
    3030                void BroadcastSealevelLoads(void);
     31                void SHDegree2Coefficients(IssmDouble* deg2coeff, FemModel* femmodel, SealevelGeometry* slgeom);
    3132};
    3233#endif  /* _SEALEVELGRDLOADS_H_ */
  • issm/trunk/src/c/classes/Inputs/TransientInput.cpp

    r26744 r27035  
    125125void TransientInput::Marshall(MarshallHandle* marshallhandle){ /*{{{*/
    126126
     127        bool isnull;
     128
    127129        int object_enum = TransientInputEnum;
    128130   marshallhandle->call(object_enum);
     
    149151        if(marshallhandle->OperationNumber()!=MARSHALLING_LOAD){
    150152                for(int i=0;i<this->numtimesteps;i++){
    151                         _assert_(this->inputs[i]);
    152                         object_enum = this->inputs[i]->ObjectEnum();
    153                         marshallhandle->call(object_enum);
    154                         this->inputs[i]->Marshall(marshallhandle);
     153
     154                        //_assert_(this->inputs[i]);
     155                        isnull = false;
     156                        if(!this->inputs[i]) isnull = true;
     157                        marshallhandle->call(isnull);
     158
     159                        if(!isnull){
     160                                object_enum = this->inputs[i]->ObjectEnum();
     161                                marshallhandle->call(object_enum);
     162                                this->inputs[i]->Marshall(marshallhandle);
     163                        }
    155164                }
    156165        }
    157166        else{
    158167                for(int i=0;i<this->numtimesteps;i++){
    159                         marshallhandle->call(object_enum);
    160 
    161                         if(object_enum==TriaInputEnum){
    162                                 TriaInput* triainput2=new TriaInput();
    163                                 triainput2->Marshall(marshallhandle);
    164                                 this->inputs[i]=triainput2;
    165                         }
    166                         else if(object_enum==PentaInputEnum){
    167                                 PentaInput* pentainput2=new PentaInput();
    168                                 pentainput2->Marshall(marshallhandle);
    169                                 this->inputs[i]=pentainput2;
    170                         }
    171                         else{
    172                                 _error_("input "<<EnumToStringx(object_enum)<<" not supported");
     168                        marshallhandle->call(isnull);
     169                        if(!isnull){
     170                                marshallhandle->call(object_enum);
     171
     172                                if(object_enum==TriaInputEnum){
     173                                        TriaInput* triainput2=new TriaInput();
     174                                        triainput2->Marshall(marshallhandle);
     175                                        this->inputs[i]=triainput2;
     176                                }
     177                                else if(object_enum==PentaInputEnum){
     178                                        PentaInput* pentainput2=new PentaInput();
     179                                        pentainput2->Marshall(marshallhandle);
     180                                        this->inputs[i]=pentainput2;
     181                                }
     182                                else{
     183                                        _error_("input "<<EnumToStringx(object_enum)<<" not supported");
     184                                }
    173185                        }
    174186                }
  • issm/trunk/src/c/classes/Loads/Channel.cpp

    r26744 r27035  
    603603        /*Initialize Element matrix and return if necessary*/
    604604        Tria*  tria=(Tria*)element;
    605         if(!tria->IsIceInElement() || this->boundary){
     605        if(!tria->IsIceInElement() || tria->IsAllFloating() || this->boundary){
    606606                this->S = 0.;
    607607                return;
  • issm/trunk/src/c/classes/Loads/Penpair.cpp

    r26744 r27035  
    355355                                default: _error_("Approximation "<<EnumToStringx(approximation1)<<" not supported yet");
    356356                        }
    357                 case MLHOApproximationEnum:
    358                         switch(approximation1){
    359                                 case MLHOApproximationEnum:   return PenaltyCreateKMatrixStressbalanceSSAHO(kmax);
     357                case MOLHOApproximationEnum:
     358                        switch(approximation1){
     359                                case MOLHOApproximationEnum:   return PenaltyCreateKMatrixStressbalanceSSAHO(kmax);
    360360                                default: _error_("Approximation "<<EnumToStringx(approximation1)<<" not supported yet");
    361361                        }
  • issm/trunk/src/c/classes/Materials/Material.h

    r26744 r27035  
    5151                virtual void       ViscosityFS(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input)=0;
    5252                virtual void       ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input)=0;
    53                 virtual void       ViscosityMLHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input)=0;
    54                 virtual void       ViscosityMLHOAdjoint(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input)=0;
     53                virtual void       ViscosityMOLHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input)=0;
     54                virtual void       ViscosityMOLHOAdjoint(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input)=0;
    5555                virtual void       ViscosityL1L2(IssmDouble* pviscosity,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* surf)=0;
    5656                virtual void       ViscositySSA(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input)=0;
  • issm/trunk/src/c/classes/Materials/Matestar.cpp

    r26744 r27035  
    567567        *pviscosity=GetViscosityGeneral(vx,vy,vz,&dvx[0],&dvy[0],&dvz[0],eps_eff,isdepthaveraged,gauss);
    568568}/*}}}*/
    569 void  Matestar::ViscosityMLHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input){/*{{{*/
    570         _error_("not implemented yet");
    571 }/*}}}*/
    572 void  Matestar::ViscosityMLHOAdjoint(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input){/*{{{*/
     569void  Matestar::ViscosityMOLHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input){/*{{{*/
     570        _error_("not implemented yet");
     571}/*}}}*/
     572void  Matestar::ViscosityMOLHOAdjoint(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input){/*{{{*/
    573573        _error_("not implemented yet");
    574574}/*}}}*/
  • issm/trunk/src/c/classes/Materials/Matestar.h

    r26744 r27035  
    7676                void       ViscosityFS(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
    7777                void       ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
    78                 void       ViscosityMLHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input);
    79                 void       ViscosityMLHOAdjoint(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input);
     78                void       ViscosityMOLHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input);
     79                void       ViscosityMOLHOAdjoint(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input);
    8080                void       ViscosityL1L2(IssmDouble* pviscosity,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* surf);
    8181                void       ViscositySSA(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
  • issm/trunk/src/c/classes/Materials/Matice.cpp

    r26744 r27035  
    394394        }
    395395        else{
    396 
    397                 /*if no strain rate, return maximum viscosity*/
    398                 if(eps_eff==0.){
    399                         viscosity = 1.e+14/2.;
    400                         //viscosity=2.5*pow(10.,17);
    401                 }
    402 
     396                /*if strain rate is 0., it is probably our initial guess, use an average
     397                 * viscosity instead of a large one*/
     398                if(eps_eff==0.) viscosity = 1.e+14/2.;
    403399                else{
     400                        /*if no strain rate, return maximum viscosity*/
     401                        //if(eps_eff<1.e-6) eps_eff = 1e-6;
    404402                        viscosity=(1.-D)*B/(2.*pow(E,1./n)*pow(eps_eff,(n-1.)/n));
    405403                }
     
    736734        *pviscosity=viscosity;
    737735}/*}}}*/
    738 void  Matice::ViscosityMLHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vxbase_input,Input* vybase_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input){/*{{{*/
     736void  Matice::ViscosityMOLHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vxbase_input,Input* vybase_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input){/*{{{*/
    739737
    740738        /*Intermediaries*/
     
    757755
    758756                /* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy (for a given zeta)*/
    759                 element->StrainRateMLHO(&epsilon[0],xyz_list,gauss,
     757                element->StrainRateMOLHO(&epsilon[0],xyz_list,gauss,
    760758                                                vxbase_input,vybase_input,vxshear_input,vyshear_input,thickness_input,n_input,zeta);
    761759                epsilon_eff=sqrt(epsilon[0]*epsilon[0] + epsilon[1]*epsilon[1] + epsilon[2]*epsilon[2]
     
    797795        delete gauss_seg;
    798796}/*}}}*/
    799 void  Matice::ViscosityMLHOAdjoint(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vxbase_input,Input* vybase_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input){/*{{{*/
     797void  Matice::ViscosityMOLHOAdjoint(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vxbase_input,Input* vybase_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input){/*{{{*/
    800798
    801799        /* To compute the additional 5 terms in the viscosity appear in the adjoint equation*/
     
    819817
    820818                /* eps_eff^2 = exx^2 + eyy^2 + exy^2 + exz^2 + eyz^2 + exx*eyy (for a given zeta)*/
    821                 element->StrainRateMLHO(&epsilon[0],xyz_list,gauss,
     819                element->StrainRateMOLHO(&epsilon[0],xyz_list,gauss,
    822820                                                vxbase_input,vybase_input,vxshear_input,vyshear_input,thickness_input,n_input,zeta);
    823821                epsilon_eff=sqrt(epsilon[0]*epsilon[0] + epsilon[1]*epsilon[1] + epsilon[2]*epsilon[2]
  • issm/trunk/src/c/classes/Materials/Matice.h

    r26744 r27035  
    7878                void       ViscosityFS(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input);
    7979                void       ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
    80                 void       ViscosityMLHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input);
    81                 void       ViscosityMLHOAdjoint(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input);
     80                void       ViscosityMOLHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input);
     81                void       ViscosityMOLHOAdjoint(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input);
    8282                void       ViscosityL1L2(IssmDouble* pviscosity,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* surf);
    8383                void       ViscositySSA(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input);
  • issm/trunk/src/c/classes/Materials/Matlitho.h

    r26744 r27035  
    7272                void       ViscosityFS(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vz_input){_error_("not supported");};
    7373                void       ViscosityHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){_error_("not supported");};
    74                 void       ViscosityMLHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input){_error_("not supported");};
    75                 void       ViscosityMLHOAdjoint(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input){_error_("not supported");};
     74                void       ViscosityMOLHO(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input){_error_("not supported");};
     75                void       ViscosityMOLHOAdjoint(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* vxshear_input,Input* vyshear_input,Input* thickness_input,Input* n_input){_error_("not supported");};
    7676                void       ViscosityL1L2(IssmDouble* pviscosity,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input,Input* surf){_error_("not supported");};
    7777                void       ViscositySSA(IssmDouble* pviscosity,int dim,IssmDouble* xyz_list,Gauss* gauss,Input* vx_input,Input* vy_input){_error_("not supported");};
  • issm/trunk/src/c/classes/Node.cpp

    r26744 r27035  
    118118                                this->HardDeactivate();
    119119                        }
    120                         if(in_approximation==MLHOApproximationEnum && !reCast<int>(iomodel->Data("md.mesh.vertexonbase")[io_index])){
     120                        if(in_approximation==MOLHOApproximationEnum && !reCast<int>(iomodel->Data("md.mesh.vertexonbase")[io_index])){
    121121                                this->HardDeactivate();
    122122                        }
  • issm/trunk/src/c/classes/Radar.h

    r26744 r27035  
    1111
    1212IssmDouble OutputDefinitionsResponsex(FemModel* femmodel,int output_enum);
    13 void  GetVectorFromInputsx( IssmDouble** pvector, int* pvector_size, FemModel* femmodel,int name);
    1413
    1514class Radar: public Object, public Definition{
  • issm/trunk/src/c/classes/SealevelGeometry.cpp

    r26744 r27035  
    3535                nsubel[i]=0;
    3636                nbar[i]=0;
     37                Ylm_subel[i]= xNewZeroInit<IssmDouble>(localnel*9);
    3738        }
    3839        late=xNew<IssmDouble>(localnel);
     
    4041        isoceanin=xNew<bool>(localnel);
    4142        lids=xNew<int>(localnodsin);
     43        Ylm=xNewZeroInit<IssmDouble>(localnel*9); // (degmax+1)^2 terms, degmax=2
    4244
    4345}; /*}}}*/
     
    5658                xDelete<IssmDouble>(longbarycentre[i]);
    5759                xDelete<IssmDouble>(area_subel[i]);
    58         }
     60                xDelete<IssmDouble>(Ylm_subel[i]);
     61        }
     62        xDelete<IssmDouble>(Ylm);
    5963        xDelete<IssmDouble>(late);
    6064        xDelete<IssmDouble>(longe);
     
    7175        for (int i=0;i<SLGEOM_NUMLOADS;i++){
    7276                subelementmapping[i]=xNew<int>(localnel);
     77                #ifdef _HAVE_PETSC_
    7378                GetOwnershipBoundariesFromRange(&lower_row,&dummy,nsubel[i],IssmComm::GetComm());
     79                #else
     80                _error_("not supported without PETSc compiled");
     81                #endif
    7482
    7583                int count=0;
     
    155163
    156164} /*}}}*/
     165void SealevelGeometry::BuildSphericalHarmonics(){ /*{{{*/
     166        //builds spherical harmonics functions for degrees 0, 1, 2 on centroids/barycenters
     167        //0: used for global average
     168        //1: used for geocenter motion
     169        //2: used for rotational feedback
     170        int intj, count;
     171
     172        IssmDouble YlmNorm[9];
     173
     174        //YlmNormalization: N^2=(2*l+1)/4/pi * factorial(l-m)/factorial(l+m) if m==0
     175        //             : 2*N^2 if m>0
     176        // such that integral(Ylm * Ylm *YlmNorm dS) = 1 on the unit sphere.
     177        YlmNorm[0]=(0.25/M_PI); //Y00
     178        YlmNorm[1]=(0.75/M_PI); //Y10
     179        YlmNorm[2]=(0.75/M_PI); //Y11c
     180        YlmNorm[3]=YlmNorm[2];   //Y11s
     181        YlmNorm[4]=(1.25/M_PI); //Y20
     182        YlmNorm[5]=(1.25/3./M_PI); //Y21c
     183        YlmNorm[6]=YlmNorm[5]; //Y21s
     184        YlmNorm[7]=(1.25/12./M_PI); //Y22c
     185        YlmNorm[8]=YlmNorm[7]; //Y22s
     186
     187        for (int e=0;e<localnel;e++){
     188                IssmDouble lat=late[e]*M_PI/180.;
     189                IssmDouble lon=longe[e]*M_PI/180.;
     190                Ylm[0*localnel+e] = 1.0 *YlmNorm[0]; //Y00
     191
     192                Ylm[1*localnel+e] = sin(lat)*YlmNorm[1]; //Y10
     193                Ylm[2*localnel+e] = cos(lat)*cos(lon)*YlmNorm[2]; //Y11cos
     194                Ylm[3*localnel+e] = cos(lat)*sin(lon)*YlmNorm[3]; //Y11sin
     195
     196                //Ylm[4*localnel+e] = 0.25 - 0.75*cos(2.0*lat) ; //Y20
     197                Ylm[4*localnel+e] = (1.5*pow(sin(lat),2.)-0.5)*YlmNorm[4]; //Y20
     198                Ylm[5*localnel+e] = 1.5*sin(2.*lat)*cos(lon)*YlmNorm[5]; //Y21cos
     199                Ylm[6*localnel+e] = 1.5*sin(2.*lat)*sin(lon)*YlmNorm[6]; //Y21sin
     200                Ylm[7*localnel+e] = 1.5*(1.+cos(2.*lat))*cos(2.*lon)*YlmNorm[7]; //Y22cos
     201                Ylm[8*localnel+e] = 1.5*(1.+cos(2.*lat))*sin(2.*lon)*YlmNorm[8]; //Y22sin
     202        }
     203
     204        for (int i=0;i<SLGEOM_NUMLOADS;i++){
     205                for (int e=0;e<localnel;e++){
     206                        if (issubelement[i][e]){
     207                                intj=subelementmapping[i][e];
     208                                IssmDouble lat=latbarycentre[i][intj]*M_PI/180.;
     209                                IssmDouble lon=longbarycentre[i][intj]*M_PI/180.;
     210                                Ylm_subel[i][0*localnel+e] = 1.0*YlmNorm[0]; //Y00
     211
     212                                Ylm_subel[i][1*localnel+e] = sin(lat)*YlmNorm[1]; //Y10
     213                                Ylm_subel[i][2*localnel+e] = cos(lat)*cos(lon)*YlmNorm[2]; //Y11cos
     214                                Ylm_subel[i][3*localnel+e] = cos(lat)*sin(lon)*YlmNorm[3]; //Y11sin
     215
     216                                Ylm_subel[i][4*localnel+e] = (1.5*pow(sin(lat),2.)-0.5)*YlmNorm[4]; //Y20
     217                                Ylm_subel[i][5*localnel+e] = 1.5*sin(2.*lat)*cos(lon)*YlmNorm[5]; //Y21cos
     218                                Ylm_subel[i][6*localnel+e] = 1.5*sin(2.*lat)*sin(lon)*YlmNorm[6]; //Y21sin
     219                                Ylm_subel[i][7*localnel+e] = 1.5*(1.+cos(2.*lat))*cos(2.*lon)*YlmNorm[7]; //Y22cos
     220                                Ylm_subel[i][8*localnel+e] = 1.5*(1.+cos(2.*lat))*sin(2.*lon)*YlmNorm[8]; //Y22sin
     221                        }
     222                }
     223        }
     224} /*}}}*/
  • issm/trunk/src/c/classes/SealevelGeometry.h

    r26744 r27035  
    1414
    1515#include "../toolkits/toolkits.h"
     16#include "../classes/classes.h"
    1617
    1718class SealevelGeometry{
     
    3031                IssmDouble* late;
    3132                IssmDouble* longe;
     33                IssmDouble* Ylm;
     34                IssmDouble* Ylm_subel[SLGEOM_NUMLOADS];
     35                IssmDouble* YlmNorm[9];
    3236                bool* isoceanin;
    3337                bool*       issubelement[SLGEOM_NUMLOADS];
     
    4549                int GNEnum(int l);
    4650                int GEEnum(int l);
     51                void BuildSphericalHarmonics(void);
    4752};
    4853#endif  /* _SEALEVELGEOMETRY_H_ */
  • issm/trunk/src/c/classes/matrix/ElementMatrix.cpp

    r26744 r27035  
    260260        _printf_("   sglobaldoflist  (" << sglobaldoflist << "): ");
    261261        for(i=0;i<nrows;i++)_printf_(" " << sglobaldoflist[i]); _printf_(" \n");
     262}
     263/*}}}*/
     264bool ElementMatrix::HasDof(int dof,int set){/*{{{*/
     265
     266        if(set==FsetEnum){
     267                for(int i=0;i<this->nrows;i++) if(this->fglobaldoflist[i] == dof) return true;
     268        }
     269        else if(set==GsetEnum){
     270                for(int i=0;i<this->nrows;i++) if(this->gglobaldoflist[i] == dof) return true;
     271        }
     272        else if(set==SsetEnum){
     273                for(int i=0;i<this->nrows;i++) if(this->sglobaldoflist[i] == dof) return true;
     274        }
     275        else{
     276                _error_("not supported yet");
     277        }
     278
     279        return false;
    262280}
    263281/*}}}*/
  • issm/trunk/src/c/classes/matrix/ElementMatrix.h

    r26744 r27035  
    4646                void StaticCondensation(int numindices,int* indices);
    4747                void Transpose(void);
     48                bool HasDof(int dof,int set);
    4849};
    4950#endif //#ifndef _ELEMENT_MATRIX_H_
  • issm/trunk/src/c/cores/ProcessArguments.cpp

    r25836 r27035  
    2929
    3030        /*Create all file paths*/
    31         char* binfilename      = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".bin")      +1); sprintf(binfilename,   "%s%s%s",rootpath,modelname,".bin");
    32         char* outbinfilename   = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".outbin")   +1); sprintf(outbinfilename,"%s%s%s",rootpath,modelname,".outbin");
    33         char* toolkitsfilename = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".toolkits") +1); sprintf(toolkitsfilename,"%s%s%s",rootpath,modelname,".toolkits");
    34         char* lockfilename     = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".lock")     +1); sprintf(lockfilename,  "%s%s%s",rootpath,modelname,".lock");
    35         char* restartfilename  = xNew<char>(strlen(rootpath)+strlen(modelname)+strlen(".rst.")+rank_length+1);
    36         sprintf(restartfilename,"%s%s%s%i",rootpath,modelname,".rst.",my_rank);
     31        int   base_length = strlen(rootpath)+strlen(modelname);
     32        char* binfilename      = xNew<char>(base_length+strlen(".bin")     +1); sprintf(binfilename,   "%s%s%s",rootpath,modelname,".bin");
     33        char* outbinfilename   = xNew<char>(base_length+strlen(".outbin")  +1); sprintf(outbinfilename,"%s%s%s",rootpath,modelname,".outbin");
     34        char* toolkitsfilename = xNew<char>(base_length+strlen(".toolkits")+1); sprintf(toolkitsfilename,"%s%s%s",rootpath,modelname,".toolkits");
     35        char* lockfilename     = xNew<char>(base_length+strlen(".lock")    +1); sprintf(lockfilename,  "%s%s%s",rootpath,modelname,".lock");
     36        char* restartfilename  = xNew<char>(base_length+strlen("_rank")+rank_length+strlen(".rst")+1);
     37        sprintf(restartfilename,"%s%s%s%i%s",rootpath,modelname,"_rank",my_rank,".rst");
    3738
    3839        /*Clean up and assign output pointer*/
     
    4445        *prootpath=rootpath;
    4546        *pmodelname=modelname;
    46 
    4747}
  • issm/trunk/src/c/cores/bmb_core.cpp

    r24313 r27035  
    3636        FloatingiceMeltingRatex(femmodel);
    3737
    38         /*Extrude basal melt*/
    39         femmodel->parameters->SetParam(BasalforcingsFloatingiceMeltingRateEnum,InputToExtrudeEnum);
    40         extrudefrombase_core(femmodel);
     38        /*Extrude basal melt if not default melting rate (which may be a transient input that can't be extruded)*/
     39        if(basalforcing_model!=FloatingMeltRateEnum){
     40                femmodel->parameters->SetParam(BasalforcingsFloatingiceMeltingRateEnum,InputToExtrudeEnum);
     41                extrudefrombase_core(femmodel);
     42        }
    4143}
  • issm/trunk/src/c/cores/controladm1qn3_core.cpp

    r26744 r27035  
    1515#include <sstream> // for output of the CoDiPack tape
    1616#include <fenv.h>
    17 void transient_ad(FemModel* femmodel);
     17double transient_ad(FemModel* femmodel, double* G,double* Jlist);
    1818#endif
    1919
     
    222222        int    *N = NULL;
    223223        int    *control_enum    = NULL;
     224        int     checkpoint_frequency;
    224225        femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
    225226        femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
     
    228229        femmodel->parameters->FindParam(&M,NULL,ControlInputSizeMEnum);
    229230        femmodel->parameters->FindParam(&control_enum,NULL,InversionControlParametersEnum);
     231        femmodel->parameters->FindParam(&checkpoint_frequency,SettingsCheckpointFrequencyEnum);
    230232
    231233        /*Constrain input vector and update controls*/
     
    236238
    237239        int offset = 0;
    238         for (int c=0;c<num_controls;c++){
     240        for(int c=0;c<num_controls;c++){
    239241                for(int i=0;i<M[c]*N[c];i++){
    240242                        int index = offset+i;
     
    246248        }
    247249
    248         /*Start Tracing*/
    249         simul_starttrace(femmodel);
    250         /*Set X as our new control input and as INDEPENDENT*/
     250        /*Special case: do we need to run AD with checkpointing?*/
     251        #ifdef _HAVE_CODIPACK_
     252        if(checkpoint_frequency && solution_type == TransientSolutionEnum){
     253                SetControlInputsFromVectorx(femmodel,X);
     254                *pf = transient_ad(femmodel, G, &Jlist[(*Jlisti)*JlistN]);
     255        }
     256        else
     257        #endif
     258          {
     259
     260                /*Start Tracing*/
     261                simul_starttrace(femmodel);
     262                /*Set X as our new control input and as INDEPENDENT*/
    251263#ifdef _HAVE_AD_
    252         IssmDouble* aX=xNew<IssmDouble>(intn,"t");
     264                IssmDouble* aX=xNew<IssmDouble>(intn,"t");
    253265#else
    254         IssmDouble* aX=xNew<IssmDouble>(intn);
     266                IssmDouble* aX=xNew<IssmDouble>(intn);
    255267#endif
    256268
    257         #if defined(_HAVE_ADOLC_)
    258         if(my_rank==0){
    259                 for(int i=0;i<intn;i++){
    260                         aX[i]<<=X[i];
    261                 }
    262         }
    263         #elif defined(_HAVE_CODIPACK_)
    264 
    265         /*Get tape*/
    266         #if _CODIPACK_MAJOR_==2
    267         auto& tape_codi = IssmDouble::getTape();
    268         #elif _CODIPACK_MAJOR_==1
    269         auto& tape_codi = IssmDouble::getGlobalTape();
    270         #else
    271         #error "_CODIPACK_MAJOR_ not supported"
    272         #endif
    273 
    274         codi_global.input_indices.clear();
    275         if(my_rank==0){
    276                 for (int i=0;i<intn;i++) {
    277                         aX[i]=X[i];
    278                         tape_codi.registerInput(aX[i]);
    279                         #if _CODIPACK_MAJOR_==2
    280                         codi_global.input_indices.push_back(aX[i].getIdentifier());
    281                         #elif _CODIPACK_MAJOR_==1
    282                         codi_global.input_indices.push_back(aX[i].getGradientData());
    283                         #else
    284                         #error "_CODIPACK_MAJOR_ not supported"
    285                         #endif
    286 
    287                 }
    288         }
    289         #else
    290         _error_("not suppoted");
    291         #endif
    292 
    293         ISSM_MPI_Bcast(aX,intn,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
    294         SetControlInputsFromVectorx(femmodel,aX);
    295         xDelete<IssmDouble>(aX);
    296 
    297         /*Compute solution (forward)*/
    298         void (*solutioncore)(FemModel*)=NULL;
    299         CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
    300         solutioncore(femmodel);
    301 
    302         /*Get Dependents*/
    303         IssmDouble   output_value;
    304         int          num_dependents;
    305         IssmPDouble *dependents;
    306         IssmDouble   J = 0.;
    307         DataSet     *dependent_objects = ((DataSetParam*)femmodel->parameters->FindParamObject(AutodiffDependentObjectsEnum))->value;
    308         femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
    309 
    310         /*Go through our dependent variables, and compute the response:*/
    311         dependents=xNew<IssmPDouble>(num_dependents);
    312         #if defined(_HAVE_CODIPACK_)
    313         codi_global.output_indices.clear();
    314         #endif
    315         int i=-1;
    316         for(Object* & object:dependent_objects->objects){
    317                 i++;
    318                 DependentObject* dep=xDynamicCast<DependentObject*>(object);
    319                 if(solution_type==TransientSolutionEnum) output_value = dep->GetValue();
    320                 if(solution_type!=TransientSolutionEnum) dep->Responsex(&output_value,femmodel);
    321                 if(my_rank==0) {
     269                #if defined(_HAVE_ADOLC_)
     270                if(my_rank==0){
     271                        for(int i=0;i<intn;i++){
     272                                aX[i]<<=X[i];
     273                        }
     274                }
     275                #elif defined(_HAVE_CODIPACK_)
     276
     277                /*Get tape*/
     278                #if _CODIPACK_MAJOR_==2
     279                auto& tape_codi = IssmDouble::getTape();
     280                #elif _CODIPACK_MAJOR_==1
     281                auto& tape_codi = IssmDouble::getGlobalTape();
     282                #else
     283                #error "_CODIPACK_MAJOR_ not supported"
     284                #endif
     285
     286                codi_global.input_indices.clear();
     287                if(my_rank==0){
     288                        for (int i=0;i<intn;i++) {
     289                                aX[i]=X[i];
     290                                tape_codi.registerInput(aX[i]);
     291                                #if _CODIPACK_MAJOR_==2
     292                                codi_global.input_indices.push_back(aX[i].getIdentifier());
     293                                #elif _CODIPACK_MAJOR_==1
     294                                codi_global.input_indices.push_back(aX[i].getGradientData());
     295                                #else
     296                                #error "_CODIPACK_MAJOR_ not supported"
     297                                #endif
     298
     299                        }
     300                }
     301                #else
     302                _error_("not suppoted");
     303                #endif
     304
     305                ISSM_MPI_Bcast(aX,intn,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
     306                SetControlInputsFromVectorx(femmodel,aX);
     307                xDelete<IssmDouble>(aX);
     308
     309                /*Compute solution (forward)*/
     310                void (*solutioncore)(FemModel*)=NULL;
     311                CorePointerFromSolutionEnum(&solutioncore,femmodel->parameters,solution_type);
     312                solutioncore(femmodel);
     313
     314                /*Get Dependents*/
     315                IssmDouble   output_value;
     316                int          num_dependents;
     317                IssmPDouble *dependents;
     318                IssmDouble   J = 0.;
     319                DataSet     *dependent_objects = ((DataSetParam*)femmodel->parameters->FindParamObject(AutodiffDependentObjectsEnum))->value;
     320                femmodel->parameters->FindParam(&num_dependents,AutodiffNumDependentsEnum);
     321
     322                /*Go through our dependent variables, and compute the response:*/
     323                dependents=xNew<IssmPDouble>(num_dependents);
     324                #if defined(_HAVE_CODIPACK_)
     325                codi_global.output_indices.clear();
     326                #endif
     327                int i=-1;
     328                for(Object* & object:dependent_objects->objects){
     329                        i++;
     330                        DependentObject* dep=xDynamicCast<DependentObject*>(object);
     331                        if(solution_type==TransientSolutionEnum) output_value = dep->GetValue();
     332                        if(solution_type!=TransientSolutionEnum) dep->Responsex(&output_value,femmodel);
    322333
    323334                        #if defined(_HAVE_CODIPACK_)
     
    340351                        J+=output_value;
    341352                }
    342         }
    343 
    344         /*Turning off trace tape*/
    345         simul_stoptrace();
    346 
    347         /*intermediary: */
    348         int          num_independents=intn;
    349         IssmPDouble *aWeightVector=NULL;
    350         IssmPDouble *weightVectorTimesJac=NULL;
    351         IssmPDouble *totalgradient=xNewZeroInit<IssmPDouble>(num_independents);
    352 
    353         /*if no dependents, no point in running a driver: */
    354         if(!(num_dependents*num_independents)) _error_("this is not allowed");
    355 
    356         /*for adolc to run in parallel, we 0 out on rank~=0. But we still keep track of num_dependents:*/
    357         int num_dependents_old   = num_dependents;
    358         int num_independents_old = num_independents;
    359 
    360         #if defined(_HAVE_ADOLC_)
    361         /*Get gradient for ADOLC {{{*/
    362         if(my_rank!=0){
    363                 num_dependents   = 0;
    364                 num_independents = 0;
    365         }
    366 
    367         /*get the EDF pointer:*/
    368         ext_diff_fct *anEDF_for_solverx_p=xDynamicCast<GenericParam<Adolc_edf> * >(femmodel->parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p;
    369 
    370         /* these are always needed regardless of the interpreter */
    371         anEDF_for_solverx_p->dp_x=xNew<double>(anEDF_for_solverx_p->max_n);
    372         anEDF_for_solverx_p->dp_y=xNew<double>(anEDF_for_solverx_p->max_m);
    373 
    374         /* Ok, now we are going to call the fos_reverse in a loop on the index, from 0 to num_dependents, so
    375          * as to generate num_dependents gradients: */
    376         for(int aDepIndex=0;aDepIndex<num_dependents_old;aDepIndex++){
    377 
    378                 /*initialize direction index in the weights vector: */
    379                 aWeightVector=xNewZeroInit<IssmPDouble>(num_dependents);
    380                 if (my_rank==0) aWeightVector[aDepIndex]=1.;
    381 
    382                 /*initialize output gradient: */
    383                 weightVectorTimesJac=xNew<IssmPDouble>(num_independents);
    384 
    385                 /*set the forward method function pointer: */
    386                 #ifdef _HAVE_GSL_
    387                 anEDF_for_solverx_p->fos_reverse=EDF_fos_reverse_for_solverx;
    388                 #endif
    389                 #ifdef _HAVE_MUMPS_
    390                 anEDF_for_solverx_p->fos_reverse_iArr=fos_reverse_mumpsSolveEDF;
    391                 #endif
    392 
    393                 anEDF_for_solverx_p->dp_U=xNew<IssmPDouble>(anEDF_for_solverx_p->max_m);
    394                 anEDF_for_solverx_p->dp_Z=xNew<IssmPDouble>(anEDF_for_solverx_p->max_n);
    395 
    396                 /*call driver: */
    397                 fos_reverse(my_rank,num_dependents,num_independents, aWeightVector, weightVectorTimesJac );
    398 
    399                 /*Add to totalgradient: */
    400                 if(my_rank==0) for(int i=0;i<num_independents;i++) {
    401                         totalgradient[i]+=weightVectorTimesJac[i];
    402                 }
    403 
    404                 /*free resources :*/
    405                 xDelete(weightVectorTimesJac);
    406                 xDelete(aWeightVector);
    407         }
    408         /*}}}*/
    409         #elif defined(_HAVE_CODIPACK_)
    410         /*Get gradient for CoDiPack{{{*/
    411         if(VerboseAutodiff())_printf0_("   CoDiPack fos_reverse\n");
    412 
    413         /* call the fos_reverse in a loop on the index, from 0 to num_dependents, so
    414          * as to generate num_dependents gradients: */
    415         for(int dep_index=0;dep_index<num_dependents_old;dep_index++){
    416 
    417                 /*initialize direction index in the weights vector: */
    418                 if(my_rank==0){
    419                         if(dep_index<0 || dep_index>=num_dependents || codi_global.output_indices.size() <= dep_index){
    420                                 _error_("index value for dependent index should be in [0,num_dependents-1]");
     353
     354                /*Turning off trace tape*/
     355                simul_stoptrace();
     356
     357                /*intermediary: */
     358                int          num_independents=intn;
     359                IssmPDouble *aWeightVector=NULL;
     360                IssmPDouble *weightVectorTimesJac=NULL;
     361                IssmPDouble *totalgradient=xNewZeroInit<IssmPDouble>(num_independents);
     362
     363                /*if no dependents, no point in running a driver: */
     364                if(!(num_dependents*num_independents)) _error_("this is not allowed");
     365
     366                /*for adolc to run in parallel, we 0 out on rank~=0. But we still keep track of num_dependents:*/
     367                int num_dependents_old   = num_dependents;
     368                int num_independents_old = num_independents;
     369
     370                #if defined(_HAVE_ADOLC_)
     371                /*Get gradient for ADOLC {{{*/
     372                if(my_rank!=0){
     373                        num_dependents   = 0;
     374                        num_independents = 0;
     375                }
     376
     377                /*get the EDF pointer:*/
     378                ext_diff_fct *anEDF_for_solverx_p=xDynamicCast<GenericParam<Adolc_edf> * >(femmodel->parameters->FindParamObject(AdolcParamEnum))->GetParameterValue().myEDF_for_solverx_p;
     379
     380                /* these are always needed regardless of the interpreter */
     381                anEDF_for_solverx_p->dp_x=xNew<double>(anEDF_for_solverx_p->max_n);
     382                anEDF_for_solverx_p->dp_y=xNew<double>(anEDF_for_solverx_p->max_m);
     383
     384                /* Ok, now we are going to call the fos_reverse in a loop on the index, from 0 to num_dependents, so
     385                 * as to generate num_dependents gradients: */
     386                for(int aDepIndex=0;aDepIndex<num_dependents_old;aDepIndex++){
     387
     388                        /*initialize direction index in the weights vector: */
     389                        aWeightVector=xNewZeroInit<IssmPDouble>(num_dependents);
     390                        if (my_rank==0) aWeightVector[aDepIndex]=1.;
     391
     392                        /*initialize output gradient: */
     393                        weightVectorTimesJac=xNew<IssmPDouble>(num_independents);
     394
     395                        /*set the forward method function pointer: */
     396                        #ifdef _HAVE_GSL_
     397                        anEDF_for_solverx_p->fos_reverse=EDF_fos_reverse_for_solverx;
     398                        #endif
     399                        #ifdef _HAVE_MUMPS_
     400                        anEDF_for_solverx_p->fos_reverse_iArr=fos_reverse_mumpsSolveEDF;
     401                        #endif
     402
     403                        anEDF_for_solverx_p->dp_U=xNew<IssmPDouble>(anEDF_for_solverx_p->max_m);
     404                        anEDF_for_solverx_p->dp_Z=xNew<IssmPDouble>(anEDF_for_solverx_p->max_n);
     405
     406                        /*call driver: */
     407                        fos_reverse(my_rank,num_dependents,num_independents, aWeightVector, weightVectorTimesJac );
     408
     409                        /*Add to totalgradient: */
     410                        if(my_rank==0) for(int i=0;i<num_independents;i++) {
     411                                totalgradient[i]+=weightVectorTimesJac[i];
    421412                        }
    422                         tape_codi.setGradient(codi_global.output_indices[dep_index],1.0);
    423                 }
    424                 //feclearexcept(FE_ALL_EXCEPT);
    425                 //feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
    426                 tape_codi.evaluate();
    427 
    428                 /*Get gradient for this dependent */
    429                 weightVectorTimesJac=xNew<IssmPDouble>(num_independents);
    430                 auto in_size = codi_global.input_indices.size();
    431                 for(size_t i = 0; i < in_size; ++i){
    432                         _assert_(i<num_independents);
    433                         weightVectorTimesJac[i] = tape_codi.getGradient(codi_global.input_indices[i]);
    434                 }
    435                 if(my_rank==0) for(int i=0;i<num_independents;i++){
    436                         totalgradient[i]+=weightVectorTimesJac[i];
    437                 }
    438                 xDelete(weightVectorTimesJac);
    439         }
    440 
    441         /*Clear tape*/
    442         tape_codi.reset();
    443         /*}}}*/
    444         #else
    445         _error_("not suppoted");
    446         #endif
    447 
    448         /*Broadcast gradient to other ranks*/
    449         ISSM_MPI_Bcast(totalgradient,num_independents_old,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
    450         /*Check size of Jlist to avoid crashes*/
    451         _assert_((*Jlisti)<JlistM);
    452         _assert_(JlistN==num_responses+1);
    453 
    454         /*Compute objective function and broadcast it to other cpus*/
    455         *pf = reCast<double>(J);
    456         ISSM_MPI_Bcast(pf,1,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
    457         _printf0_("f(x) = "<<setw(12)<<setprecision(7)<<*pf<<"  |  ");
    458 
    459         /*Record cost function values and delete Jtemp*/
    460         for(int i=0;i<num_responses;i++) Jlist[(*Jlisti)*JlistN+i] = dependents[i];
    461         Jlist[(*Jlisti)*JlistN+num_responses] = reCast<IssmPDouble>(J);
    462 
    463         if(*indic==0){
    464                 /*dry run, no gradient required*/
    465 
    466                 /*Retrieve objective functions independently*/
    467                 _printf0_("            N/A |\n");
    468                 for(int i=0;i<num_responses;i++) _printf0_(" "<<setw(12)<<setprecision(7)<<Jlist[(*Jlisti)*JlistN+i]);
    469                 _printf0_("\n");
    470 
    471                 *Jlisti = (*Jlisti) +1;
    472                 xDelete<double>(XU);
    473                 xDelete<double>(XL);
    474                 return;
    475         }
    476 
    477         /*Compute gradient*/
    478         for(long i=0;i<num_independents_old;i++) G[i] = totalgradient[i];
     413
     414                        /*free resources :*/
     415                        xDelete(weightVectorTimesJac);
     416                        xDelete(aWeightVector);
     417                }
     418                /*}}}*/
     419                #elif defined(_HAVE_CODIPACK_)
     420                /*Get gradient for CoDiPack{{{*/
     421                if(VerboseAutodiff())_printf0_("   CoDiPack fos_reverse\n");
     422
     423                /* call the fos_reverse in a loop on the index, from 0 to num_dependents, so
     424                 * as to generate num_dependents gradients: */
     425                for(int dep_index=0;dep_index<num_dependents_old;dep_index++){
     426
     427                        /*initialize direction index in the weights vector: */
     428                        if(my_rank==0){
     429                                if(dep_index<0 || dep_index>=num_dependents || codi_global.output_indices.size() <= dep_index){
     430                                        _error_("index value for dependent index should be in [0,num_dependents-1]");
     431                                }
     432                                tape_codi.setGradient(codi_global.output_indices[dep_index],1.0);
     433                        }
     434                        //feclearexcept(FE_ALL_EXCEPT);
     435                        //feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
     436                        tape_codi.evaluate();
     437
     438                        /*Get gradient for this dependent */
     439                        weightVectorTimesJac=xNew<IssmPDouble>(num_independents);
     440                        auto in_size = codi_global.input_indices.size();
     441                        for(size_t i = 0; i < in_size; ++i){
     442                                _assert_(i<num_independents);
     443                                weightVectorTimesJac[i] = tape_codi.getGradient(codi_global.input_indices[i]);
     444                        }
     445                        if(my_rank==0) for(int i=0;i<num_independents;i++){
     446                                totalgradient[i]+=weightVectorTimesJac[i];
     447                        }
     448                        xDelete(weightVectorTimesJac);
     449                }
     450
     451                /*Clear tape*/
     452                tape_codi.reset();
     453                /*}}}*/
     454                #else
     455                _error_("not suppoted");
     456                #endif
     457
     458                /*Broadcast gradient to other ranks*/
     459                ISSM_MPI_Bcast(totalgradient,num_independents_old,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
     460
     461                /*Check size of Jlist to avoid crashes*/
     462                _assert_((*Jlisti)<JlistM);
     463                _assert_(JlistN==num_responses+1);
     464
     465                /*Compute objective function and broadcast it to other cpus*/
     466                *pf = reCast<double>(J);
     467                ISSM_MPI_Bcast(pf,1,ISSM_MPI_PDOUBLE,0,IssmComm::GetComm());
     468
     469                /*Record cost function values and delete Jtemp*/
     470                for(int i=0;i<num_responses;i++) Jlist[(*Jlisti)*JlistN+i] = dependents[i];
     471                Jlist[(*Jlisti)*JlistN+num_responses] = reCast<IssmPDouble>(J);
     472
     473                if(*indic==0){
     474                        /*dry run, no gradient required*/
     475
     476                        /*Retrieve objective functions independently*/
     477                        _printf0_("f(x) = "<<setw(12)<<setprecision(7)<<*pf<<"  |  ");
     478                        _printf0_("            N/A |\n");
     479                        for(int i=0;i<num_responses;i++) _printf0_(" "<<setw(12)<<setprecision(7)<<Jlist[(*Jlisti)*JlistN+i]);
     480                        _printf0_("\n");
     481
     482                        *Jlisti = (*Jlisti) +1;
     483                        xDelete<double>(XU);
     484                        xDelete<double>(XL);
     485                        return;
     486                }
     487
     488                /*Compute gradient*/
     489                for(long i=0;i<num_independents_old;i++) G[i] = totalgradient[i];
     490
     491                xDelete<IssmPDouble>(dependents);
     492                xDelete<IssmPDouble>(totalgradient);
     493          } /*====????*/
    479494
    480495        /*Constrain Gradient*/
     
    496511
    497512        /*Print info*/
     513        _printf0_("f(x) = "<<setw(12)<<setprecision(7)<<*pf<<"  |  ");
    498514        _printf0_("       "<<setw(12)<<setprecision(7)<<Gnorm<<" |");
    499515        for(int i=0;i<num_responses;i++) _printf0_(" "<<setw(12)<<setprecision(7)<<Jlist[(*Jlisti)*JlistN+i]);
     
    509525        xDelete<int>(N);
    510526        xDelete<double>(scaling_factors);
    511         xDelete<IssmPDouble>(dependents);
    512         xDelete<IssmPDouble>(totalgradient);
    513527}/*}}}*/
    514528void controladm1qn3_core(FemModel* femmodel){/*{{{*/
    515529
    516         int checkpoint_frequency;
    517         femmodel->parameters->FindParam(&checkpoint_frequency,SettingsCheckpointFrequencyEnum);
    518         if(checkpoint_frequency){
    519                 #ifdef _HAVE_CODIPACK_
    520                 transient_ad(femmodel);
    521                 femmodel->OutputControlsx(&femmodel->results);
    522                 printf("No optimization implemented yet, skipping\n");
    523                 return;
    524                 #else
    525                 _error_("checkpointing not implemented for ADOLC");
    526                 #endif
    527         }
    528530
    529531        /*Intermediaries*/
  • issm/trunk/src/c/cores/controltao_core.cpp

    r25836 r27035  
    9595        GetVectorFromControlInputsx(&XL,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"lowerbound");
    9696        GetVectorFromControlInputsx(&XU,femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,"upperbound");
     97        #if PETSC_VERSION_LT(3,17,0)
    9798        TaoSetInitialVector(tao,X->pvector->vector);
     99        #else
     100        //TaoSetSolution(tao,X->pvector->vector);
     101        _error_("not implemented yet");
     102        #endif
    98103        TaoSetVariableBounds(tao,XL->pvector->vector,XU->pvector->vector);
    99104        delete XL;
     
    110115
    111116        /*Save results*/
     117        #if PETSC_VERSION_LT(3,17,0)
    112118        TaoGetSolutionVector(tao,&X->pvector->vector);
     119        #else
     120        TaoGetSolution(tao,&X->pvector->vector);
     121        #endif
    113122        G=new Vector<IssmDouble>(0); VecFree(&G->pvector->vector);
     123        #if PETSC_VERSION_LT(3,17,0)
    114124        TaoGetGradientVector(tao,&G->pvector->vector);
     125        #else
     126        //TaoGetGradient(tao,&G->pvector->vector);
     127        _error_("not implemented yet");
     128        #endif
    115129        SetControlInputsFromVectorx(femmodel,X);
    116130        ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,G);
  • issm/trunk/src/c/cores/groundingline_core.cpp

    r25836 r27035  
    1616
    1717        /* intermediaries */
     18        int numoutputs;
    1819        bool save_results;
     20        char** requested_outputs = NULL;
    1921
    2022        /* recover parameters */
    2123        femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
     24        femmodel->parameters->FindParam(&numoutputs,GroundinglineNumRequestedOutputsEnum);
     25        if(numoutputs) femmodel->parameters->FindParam(&requested_outputs,&numoutputs,GroundinglineRequestedOutputsEnum);
    2226
    2327        /*Move grounding line*/
     
    3337        extrudefrombase_core(femmodel);
    3438
    35         if(save_results){
    36                 int outputs[3] = {SurfaceEnum,BaseEnum,MaskOceanLevelsetEnum};
    37                 femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],3);
    38         }
     39        /*Save results*/
     40        if(save_results) femmodel->RequestedOutputsx(&femmodel->results,requested_outputs,numoutputs);
     41
     42        /*Free ressources:*/
     43   if(numoutputs){for(int i=0;i<numoutputs;i++){xDelete<char>(requested_outputs[i]);} xDelete<char*>(requested_outputs);}
    3944
    4045        /*Stop profiler*/
  • issm/trunk/src/c/cores/love_core.cpp

    r26744 r27035  
    1010#include "../solutionsequences/solutionsequences.h"
    1111#include "petscblaslapack.h"
     12#ifdef _HAVE_MPLAPACK_
     13#include <quadmath.h>
     14#include "mpblas__Float128.h"
     15#include "mplapack__Float128.h"
     16#endif
     17
     18#ifdef _HAVE_MPLAPACK_
     19_Float128 a = 0.2345234534512079875620048770134538q;
     20#endif
    1221
    1322/*local definitions:*/
     
    2029                int nyi;
    2130                int starting_layer;
     31                int* deg_layer_delete;
    2232
    2333                LoveVariables(){  /*{{{*/
     
    2737                        nyi=0;
    2838                        starting_layer=0;
     39                        deg_layer_delete=NULL;
    2940                } /*}}}*/
    30                 LoveVariables(IssmDouble* EarthMassin,IssmDouble g0in,IssmDouble r0in,int nyiin,int starting_layerin){  /*{{{*/
     41                LoveVariables(IssmDouble* EarthMassin,IssmDouble g0in,IssmDouble r0in,int nyiin,int starting_layerin, int* deg_layer_deletein){  /*{{{*/
    3142                        EarthMass=EarthMassin;
    3243                        g0=g0in;
     
    3445                        nyi=nyiin;
    3546                        starting_layer=starting_layerin;
     47                        deg_layer_delete=deg_layer_deletein;
    3648                } /*}}}*/
    3749                ~LoveVariables(){};
     50}; /*}}}*/
     51
     52template <class doubletype> class LoveNumbers{  /*{{{*/
     53
     54        public:
     55                doubletype* H;
     56                doubletype* K;
     57                doubletype* L;
     58                doubletype* Kernels;
     59                int sh_nmin, sh_nmax, nfreq, nkernels;
     60
     61                LoveNumbers(){  /*{{{*/
     62                        H=NULL;
     63                        K=NULL;
     64                        L=NULL;
     65                        Kernels=NULL;
     66                        sh_nmin=0;
     67                        sh_nmax=0;
     68                        nfreq=0;
     69                        nkernels=0;
     70                } /*}}}*/
     71                LoveNumbers(int sh_nminin, int sh_nmaxin, int nfreqin, Matlitho* matlitho){  /*{{{*/
     72                        sh_nmax=sh_nmaxin;
     73                        sh_nmin=sh_nminin;
     74                        nfreq=nfreqin;
     75                        nkernels=(sh_nmax+1)*(matlitho->numlayers+1)*6;
     76                        H=xNewZeroInit<doubletype>(nfreq*(sh_nmax+1));
     77                        K=xNewZeroInit<doubletype>(nfreq*(sh_nmax+1));
     78                        L=xNewZeroInit<doubletype>(nfreq*(sh_nmax+1));
     79                        Kernels=xNewZeroInit<doubletype>(nfreq*nkernels);
     80                } /*}}}*/
     81                void DownCastToDouble(LoveNumbers<IssmDouble>* LoveDouble){
     82                        for(int i=0;i<(sh_nmax+1)*nfreq;i++){
     83                                LoveDouble->H[i]=std::real(H[i]);
     84                                LoveDouble->K[i]=std::real(K[i]);
     85                                LoveDouble->L[i]=std::real(L[i]);
     86                        }
     87                }
     88                void LoveMPI_Gather(LoveNumbers<doubletype>* Love_local, int lower_row){
     89                        int* recvcounts=xNew<int>(IssmComm::GetSize());
     90                        int* displs=xNew<int>(IssmComm::GetSize());
     91                        int  rc;
     92                        int  offset;
     93                        int nf_local = Love_local->nfreq;
     94
     95                        /*Deal H, K, L first, as they share the same size*/
     96                        rc=(sh_nmax+1)*nf_local;
     97                        offset=(sh_nmax+1)*lower_row;
     98                        ISSM_MPI_Allgather(&rc,1,ISSM_MPI_INT,recvcounts,1,ISSM_MPI_INT,IssmComm::GetComm());
     99                        ISSM_MPI_Allgather(&offset,1,ISSM_MPI_INT,displs,1,ISSM_MPI_INT,IssmComm::GetComm());
     100                        ISSM_MPI_Allgatherv(Love_local->H, rc, ISSM_MPI_DOUBLE, H, recvcounts, displs, ISSM_MPI_DOUBLE,IssmComm::GetComm());
     101                        ISSM_MPI_Allgatherv(Love_local->K, rc, ISSM_MPI_DOUBLE, K, recvcounts, displs, ISSM_MPI_DOUBLE,IssmComm::GetComm());
     102                        ISSM_MPI_Allgatherv(Love_local->L, rc, ISSM_MPI_DOUBLE, L, recvcounts, displs, ISSM_MPI_DOUBLE,IssmComm::GetComm());
     103
     104                        /* deal with love kernels now */
     105                        rc=nf_local*nkernels;
     106                        offset=lower_row*nkernels;
     107                        ISSM_MPI_Allgather(&rc,1,ISSM_MPI_INT,recvcounts,1,ISSM_MPI_INT,IssmComm::GetComm());
     108                        ISSM_MPI_Allgather(&offset,1,ISSM_MPI_INT,displs,1,ISSM_MPI_INT,IssmComm::GetComm());
     109                        ISSM_MPI_Allgatherv(Love_local->Kernels, rc, ISSM_MPI_DOUBLE, Kernels, recvcounts, displs, ISSM_MPI_DOUBLE,IssmComm::GetComm());
     110
     111                        xDelete<int>(recvcounts);
     112                        xDelete<int>(displs);
     113                }
     114                void Copy(LoveNumbers<doubletype>* LoveDup){
     115                        for(int i=0;i<(sh_nmax+1)*nfreq;i++){
     116                                H[i]=LoveDup->H[i];
     117                                K[i]=LoveDup->K[i];
     118                                L[i]=LoveDup->L[i];
     119                        }
     120                        for(int i=0;i<nkernels*nfreq;i++){
     121                                Kernels[i]=LoveDup->Kernels[i];
     122                        }
     123                }
     124                ~LoveNumbers(){
     125                        xDelete<doubletype>(H);
     126                        xDelete<doubletype>(K);
     127                        xDelete<doubletype>(L);
     128                        xDelete<doubletype>(Kernels);
     129                };
    38130}; /*}}}*/
    39131
     
    123215        return xi;
    124216}/*}}}*/
    125 template<typename doubletype> void         postwidder_transform(doubletype* Lovet, doubletype* Lovef,int d, int t, int NTit, doubletype* xi, FemModel* femmodel){ /*{{{*/
     217template<typename doubletype> void         postwidder_transform(doubletype* Lovet, doubletype* Lovef,int d, int t, int sh_nmax,int NTit, doubletype* xi, FemModel* femmodel){ /*{{{*/
    126218        //Computes Lovet for time step t and degree d from the PW coefficients xi and the corresponding 2*NTit frequency samples in Lovef
    127219
    128         int nfreq, indxi, indf;
    129         femmodel->parameters->FindParam(&nfreq,LoveNfreqEnum);
    130         int nt=nfreq/2/NTit;
    131 
    132         indf=d*nfreq+t*2*NTit;
     220        int indxi, indf;
     221        IssmDouble PW_test;
     222        IssmDouble PW_threshold;
     223        femmodel->parameters->FindParam(&PW_threshold,LovePostWidderThresholdEnum);
     224
     225        indf=(t*2*NTit)*(sh_nmax+1)+d;
    133226        doubletype* LoveM = xNew<doubletype>(NTit);
     227
     228
     229        // test variation across frequencies tested, something with little frequency dependence is not worth going through PW tranform
     230        // that transform would also be numerically unstable
     231        PW_test = abs((Lovef[indf+(2*NTit-1)*(sh_nmax+1)]-Lovef[indf])/Lovef[indf]);
     232
     233        //if (PW_test < PW_threshold){ //elastic or fluid response: Love(t) = Love(s), we can do an early return
     234        //      Lovet[t*(sh_nmax+1)+d]=Lovef[indf];
     235        //      return;
     236        //}
     237
     238        if (PW_test==0){ //elastic or fluid response: Love(t) = Love(s), we can do an early return
     239                Lovet[t*(sh_nmax+1)+d]=Lovef[indf];
     240                return;
     241        }
    134242
    135243        for (int M=1;M<NTit+1;M++){
     
    137245                for (int k=1;k<2*M+1;k++){
    138246                        indxi=(M-1)*(2*NTit)+k-1;
    139                         LoveM[M-1]+=xi[indxi]*Lovef[indf+k-1];
     247                        LoveM[M-1]+=xi[indxi]*Lovef[indf+(k-1)*(sh_nmax+1)];
    140248                }
    141249
     
    146254                        if ( abs(LoveM[M-1]-LoveM[M-2]) > abs(LoveM[M-2]-LoveM[M-3]) &&
    147255                                        abs(LoveM[M-2]-LoveM[M-3]) > abs(LoveM[M-3]-LoveM[M-4]) ){
    148                                 Lovet[d*nt+t]=LoveM[M-3];
     256                                Lovet[t*(sh_nmax+1)+d]=LoveM[M-3];
    149257                                return;
    150258                        }
    151259                }
    152260        }
    153         Lovet[d*nt+t]=LoveM[NTit-1];
     261        Lovet[t*(sh_nmax+1)+d]=LoveM[NTit-1];
    154262}/*}}}*/
    155263template <typename doubletype> void        GetEarthRheology(doubletype* pla, doubletype* pmu, int layer_index, doubletype omega,  Matlitho* matlitho){ /*{{{*/
     
    726834
    727835}/*}}}*/
    728 template <typename doubletype> void        yi_boundary_conditions(doubletype* yi_righthandside, int deg, FemModel* femmodel, Matlitho* matlitho,LoveVariables* vars){ /*{{{*/
     836template <typename doubletype> void        yi_boundary_conditions(doubletype* yi_righthandside, int deg, FemModel* femmodel, Matlitho* matlitho,LoveVariables* vars, int forcing_type){ /*{{{*/
    729837
    730838        IssmDouble  g0,r0,mu0,ra,rb,rc;
    731         int nyi, forcing_type,icb,cmb,starting_layer;
     839        int nyi,icb,cmb,starting_layer;
    732840        IssmDouble* EarthMass;
    733841
     
    739847
    740848        femmodel->parameters->FindParam(&mu0,LoveMu0Enum);
    741         femmodel->parameters->FindParam(&forcing_type,LoveForcingTypeEnum);
    742849        femmodel->parameters->FindParam(&icb,LoveInnerCoreBoundaryEnum);
    743850        femmodel->parameters->FindParam(&cmb,LoveCoreMantleBoundaryEnum);
     
    810917        }
    811918}/*}}}*/
    812 template <typename doubletype> void        solve_yi_system(doubletype* loveh, doubletype* lovel, doubletype* lovek, int deg, doubletype omega, doubletype* yi, doubletype* rhs, FemModel* femmodel, Matlitho* matlitho, LoveVariables* vars){ /*{{{*/
     919template <typename doubletype> void        solve_yi_system(doubletype* loveh, doubletype* lovel, doubletype* lovek, int deg, doubletype omega, IssmDouble* frequencies, doubletype* yi, doubletype* rhs, FemModel* femmodel, Matlitho* matlitho, LoveVariables* vars, bool verbosecpu){ /*{{{*/
    813920
    814921        IssmDouble  g0,r0,mu0,loveratio,underflow_tol;
    815         IssmDouble* frequencies;
     922        //IssmDouble* frequencies;
    816923        int nyi,starting_layer, dummy;
    817924        bool allow_layer_deletion;
     
    827934        femmodel->parameters->FindParam(&allow_layer_deletion,LoveAllowLayerDeletionEnum);
    828935        femmodel->parameters->FindParam(&underflow_tol,LoveUnderflowTolEnum);
    829         femmodel->parameters->FindParam(&frequencies,&dummy,LoveFrequenciesEnum);
     936        //femmodel->parameters->FindParam(&frequencies,&dummy,LoveFrequenciesEnum);
    830937        IssmDouble ra=matlitho->radius[matlitho->numlayers];
    831938        bool exit=false;
    832939        int lda,ldb;
     940
    833941
    834942        for(;!exit;){ //cycles of: attempt to solve the yi system, then delete a layer if necessary
     
    854962                xDelete<int>(ipiv);
    855963
    856                 if(VerboseModule() && info!=0){
    857                         _printf0_("love core warning in DGESV : LAPACK linear equation solver couldn't resolve the system");
     964                        /*_printf_("i j yi[i+nyi*j] rhs[i]");
     965                        for (int i=0;i<nyi;i++){
     966                                        _printf_(i<<" "<<rhs[i]<<"\n");
     967                        }
     968
     969                        for (int i=0;i<nyi;i++){
     970                                for (int j=0;j<nyi;j++){
     971                                        _printf_(i<<" "<<j<<" "<<yi[i+nyi*j]<<" "<<rhs[i]<<"\n");
     972                                }
     973                        }
     974                        _error_("love core warning in DGESV : LAPACK linear equation solver couldn't resolve the system");*/
     975
     976                if(VerboseSolution() && info!=0){
    858977                        _printf_("i j yi[i+nyi*j] rhs[i]");
    859978                        for (int i=0;i<nyi;i++){
     
    862981                                }
    863982                        }
     983                        _error_("love core warning in DGESV : LAPACK linear equation solver couldn't resolve the system");
    864984                }
    865985
     
    8801000                if (abs(lovek1/lovek1s) < loveratio) loveratio = abs(lovek1/lovek1s);
    8811001
    882                 if (!allow_layer_deletion || nyi<=12 || omega!=angular_frequency<doubletype>(frequencies[0])){
     1002               
     1003
     1004                if (!allow_layer_deletion || nyi<=12 || omega!=angular_frequency<doubletype>(frequencies[0]) || deg==0){
    8831005                        goto save_results;
    8841006                        /*We are not allowed to delete layers, or there is only one layer left. We also don't want to delete
     
    8871009                }
    8881010
    889                 if (loveratio<=underflow_tol || xIsNan(loveratio) || xIsInf(loveratio)){//We need to delete a layer and try again if the ratio between deepest love number to surface love number is too low (risk of underflow) or garbage
    890                         if(VerboseSolution()){
    891                                 _printf_("\n   Degree: " << deg <<", surface/Depth Love number ratio small: "<<loveratio<<"\n");
    892                                 _printf_("    Changing the interface where the integration starts\n");
    893                                 _printf_("    New start interface: r="<< matlitho->radius[starting_layer+1] <<"m\n\n");
    894                         }
     1011                if (omega==0){ // if running elastic love_numbers, record at which degree we must delete layers, this way we synch layer deletion between cpus next time we calculate love numbers
     1012                        //We need to delete a layer and try again if the ratio between deepest love number to surface love number is too low (risk of underflow) or garbage
     1013                        if (loveratio<=underflow_tol || xIsNan(loveratio) || xIsInf(loveratio)) {
     1014                                vars->deg_layer_delete[starting_layer]=deg;
     1015                                if(VerboseSolution() && verbosecpu){
     1016                                        _printf_("\n   Degree: " << deg <<", surface/Depth Love number ratio small: "<<loveratio<<"\n");
     1017                                        _printf_("    Changing the interface where integration starts\n");
     1018                                        _printf_("    New start interface: r="<< matlitho->radius[starting_layer+1] <<"m\n\n");
     1019                                }
     1020                        }
     1021                }
     1022
     1023                if (deg==vars->deg_layer_delete[starting_layer]){ // if we are at the degree where we should delete the current layer, proceed to delete the bottom layer
     1024                        if (omega!=0 && VerboseSolution()  && verbosecpu) _printf_(", deleting layer " << starting_layer << "\n");
    8951025                        nyi-=6;
    8961026                        starting_layer+=1;
     
    9341064                xDelete<doubletype>(rhslocal);
    9351065        }
    936         xDelete<IssmDouble>(frequencies);       
     1066        //xDelete<IssmDouble>(frequencies);     
    9371067
    9381068}/*}}}*/
    939 template <typename doubletype> void        love_freq_to_temporal(doubletype* LoveHt,doubletype* LoveLt,doubletype* LoveKt,doubletype* LoveHf,doubletype* LoveLf,doubletype* LoveKf, FemModel* femmodel){ /*{{{*/
     1069template <typename doubletype> void        love_freq_to_temporal(LoveNumbers<doubletype>* Lovet, LoveNumbers<doubletype>* Tidalt, doubletype* pmtf_colineart, doubletype* pmtf_orthot, LoveNumbers<doubletype>* Lovef,LoveNumbers<doubletype>* Tidalf, IssmDouble* frequencies, FemModel* femmodel, bool verbosecpu){ /*{{{*/
    9401070        //Transforms all frequency-dependent love numbers into time-dependent love numbers
    941         int nfreq,sh_nmax,sh_nmin,indxi,indf, NTit;
    942 
    943         femmodel->parameters->FindParam(&nfreq,LoveNfreqEnum);
    944         femmodel->parameters->FindParam(&sh_nmax,LoveShNmaxEnum);
    945         femmodel->parameters->FindParam(&sh_nmin,LoveShNminEnum);
     1071        int nfreq,sh_nmax,sh_nmin,indxi,indf, NTit, forcing_type, nt;
     1072        IssmDouble kf,Omega,moi_e,moi_p,alpha;
     1073        doubletype* pmtf_colinearf=NULL;
     1074        doubletype* pmtf_orthof=NULL;
     1075        bool chandler_wobble=false;
     1076
     1077        nfreq=Lovef->nfreq;
     1078        sh_nmin=Lovef->sh_nmin;
     1079        sh_nmax=Lovef->sh_nmax;
     1080
    9461081        femmodel->parameters->FindParam(&NTit,LoveNTemporalIterationsEnum);
    9471082
    948         int nt=nfreq/2/NTit;
     1083        //Parameters for the rotationnal feedback
     1084        femmodel->parameters->FindParam(&chandler_wobble,LoveChandlerWobbleEnum);
     1085        femmodel->parameters->FindParam(&forcing_type,LoveForcingTypeEnum);
     1086        femmodel->parameters->FindParam(&kf,TidalLoveK2SecularEnum);
     1087        femmodel->parameters->FindParam(&Omega,RotationalAngularVelocityEnum);
     1088        femmodel->parameters->FindParam(&moi_e,RotationalEquatorialMoiEnum);
     1089        femmodel->parameters->FindParam(&moi_p,RotationalPolarMoiEnum);
     1090
     1091        nt=Lovet->nfreq;
    9491092        doubletype* xi=postwidder_coef<doubletype>(NTit);
     1093
     1094        if(VerboseSolution()  && verbosecpu) _printf_("   Inverse Laplace Transform... ");
    9501095
    9511096        for (int d=sh_nmin;d<sh_nmax+1;d++){
    9521097                for (int t=0;t<nt;t++){
    953                         postwidder_transform<doubletype>(LoveHt,LoveHf,d,t,NTit,xi,femmodel);
    954                         postwidder_transform<doubletype>(LoveLt,LoveLf,d,t,NTit,xi,femmodel);
    955                         postwidder_transform<doubletype>(LoveKt,LoveKf,d,t,NTit,xi,femmodel);
    956                 }
    957         }
     1098                        postwidder_transform<doubletype>(Lovet->H,Lovef->H,d,t,sh_nmax,NTit,xi,femmodel);
     1099                        postwidder_transform<doubletype>(Lovet->K,Lovef->K,d,t,sh_nmax,NTit,xi,femmodel);
     1100                        postwidder_transform<doubletype>(Lovet->L,Lovef->L,d,t,sh_nmax,NTit,xi,femmodel);
     1101                }
     1102        }
     1103
     1104        if(VerboseSolution()  && verbosecpu) _printf_("done!\n");
     1105
     1106        if (forcing_type==11){ //Let's retrieve the functions necessary for the rotational_feedback
     1107                if(VerboseSolution()  && verbosecpu) _printf_("     Transforming PMTF and tidal love numbers... ");
     1108                pmtf_colinearf = xNewZeroInit<doubletype>(3*nfreq);
     1109                pmtf_orthof = xNewZeroInit<doubletype>(3*nfreq);
     1110                int d=2;
     1111                doubletype s,R1,R2;
     1112                alpha=(moi_p-moi_e)/moi_e; //Earth flattening
     1113
     1114                if (chandler_wobble){ //Chandler Wobble is untested yet
     1115                        for (int fr=0;fr<nfreq;fr++){           
     1116                                s=angular_frequency<doubletype>(frequencies[fr]);
     1117                                R1=alpha*Omega*(1.0-Tidalf->K[fr*3+d]/kf);
     1118                                R2=1.0+alpha*Tidalf->K[fr*3+d]/kf;
     1119                                pmtf_colinearf[fr*3+d]=alpha*(1.0+Lovef->K[fr*(sh_nmax+1)+d])*(Omega*R1-pow(s,2)*R2)/(pow(R1,2.0)+pow(s*R2,2.0));
     1120                                pmtf_orthof[fr*3+d]=alpha*(1.0+Lovef->K[fr*(sh_nmax+1)+d])*s*Omega*(1.0+alpha)/(pow(R1,2.0)+pow(s*R2,2.0));
     1121                        }
     1122                }
     1123                else {
     1124                        for (int fr=0;fr<nfreq;fr++){           
     1125                                pmtf_colinearf[fr*3+d]=(1.0+Lovef->K[fr*(sh_nmax+1)+d])/(1.0-Tidalf->K[fr*3+d]/kf);
     1126                                pmtf_orthof[fr*3+d]=0.0;
     1127                        }
     1128                }
     1129                for (int t=0;t<nt;t++){
     1130                        postwidder_transform<doubletype>(Tidalt->H,Tidalf->H,2,t,2,NTit,xi,femmodel);
     1131                        postwidder_transform<doubletype>(Tidalt->K,Tidalf->K,2,t,2,NTit,xi,femmodel);
     1132                        postwidder_transform<doubletype>(Tidalt->L,Tidalf->L,2,t,2,NTit,xi,femmodel);
     1133                        postwidder_transform<doubletype>(pmtf_colineart,pmtf_colinearf,2,t,2,NTit,xi,femmodel);
     1134                        postwidder_transform<doubletype>(pmtf_orthot,pmtf_orthof,2,t,2,NTit,xi,femmodel);
     1135                }
     1136                if(VerboseSolution() && verbosecpu) _printf_("done!\n");
     1137        }
     1138
    9581139        xDelete<doubletype>(xi);
     1140        xDelete<doubletype>(pmtf_colinearf);
     1141        xDelete<doubletype>(pmtf_orthof);
     1142}/*}}}*/
     1143
     1144template <typename doubletype> void        compute_love_numbers(LoveNumbers<doubletype>* Lovef, LoveNumbers<doubletype>* Elastic, int forcing_type, int sh_cutoff, IssmDouble* frequencies, FemModel* femmodel, Matlitho* matlitho, LoveVariables* vars, bool verbosecpu){
     1145
     1146        int nstep, kernel_index,kernel_indexe,deleted_layer_offset, deg, sh_nmin, sh_nmax, nfreq;
     1147        doubletype  lovek, loveh, lovel, loveratio;
     1148        doubletype  omega;
     1149        doubletype* yi_prefactor=NULL;
     1150        doubletype* yi_righthandside=NULL;
     1151        doubletype* yi=NULL;
     1152        IssmDouble  underflow_tol;
     1153        bool freq_skip, istemporal;
     1154
     1155        femmodel->parameters->FindParam(&nstep,LoveIntStepsPerLayerEnum);
     1156        femmodel->parameters->FindParam(&istemporal,LoveIsTemporalEnum);
     1157
     1158        nfreq=Lovef->nfreq;
     1159        sh_nmin=Lovef->sh_nmin;
     1160        sh_nmax=Lovef->sh_nmax;
     1161        if (Elastic==NULL) sh_cutoff=sh_nmax;
     1162
     1163        // reset deleted layers in case we have called this function before;
     1164        vars->starting_layer=0;
     1165        vars->nyi=6*(matlitho->numlayers+1);
     1166
     1167        yi_prefactor=xNewZeroInit<doubletype>(6*6*nstep*matlitho->numlayers);
     1168        yi_righthandside=xNewZeroInit<doubletype>(vars->nyi);
     1169        yi=xNewZeroInit<doubletype>(vars->nyi*vars->nyi);
     1170
     1171        //precalculate yi coefficients that do not depend on degree or frequency
     1172        fill_yi_prefactor<doubletype>(yi_prefactor, NULL, NULL,femmodel, matlitho,vars);
     1173
     1174        if (VerboseSolution() && Elastic  && verbosecpu) _printf_("\n");
     1175
     1176        for(int deg=0;deg<2;deg++){ // calculation is in the center of mass reference frame, neutralize degree 0 and 1 mass changes
     1177                for (int fr=0;fr<nfreq;fr++){
     1178                        Lovef->K[fr*(sh_nmax+1)+deg]=-1.0;
     1179                }
     1180        }
     1181
     1182        for(int deg=sh_nmin;deg<sh_cutoff+1;deg++){
     1183                if (VerboseSolution() && Elastic && verbosecpu) {
     1184                        _printf_("\r   Degree: " << deg << "/" << sh_nmax << "    ");
     1185                }
     1186
     1187                //precalculate yi coefficients that depend on degree but not frequency
     1188                fill_yi_prefactor<doubletype>(yi_prefactor, &deg, NULL,femmodel, matlitho,vars);
     1189
     1190                for (int fr=0;fr<nfreq;fr++){
     1191                        omega=angular_frequency<doubletype>(frequencies[fr]);
     1192                       
     1193                        //precalculate yi coefficients that depend on degree and frequency
     1194                        fill_yi_prefactor<doubletype>(yi_prefactor, &deg,&omega,femmodel, matlitho,vars);
     1195
     1196                        //solve the system
     1197                        yi_boundary_conditions<doubletype>(yi_righthandside,deg,femmodel,matlitho,vars,forcing_type);
     1198                        build_yi_system<doubletype>(yi,deg,omega,yi_prefactor,femmodel,matlitho,vars);
     1199                        solve_yi_system<doubletype>(&loveh,&lovel,&lovek, deg, omega, frequencies, yi, yi_righthandside,femmodel, matlitho,vars,verbosecpu);
     1200                        Lovef->H[fr*(sh_nmax+1)+deg]=loveh;
     1201                        Lovef->K[fr*(sh_nmax+1)+deg]=lovek-1.0;
     1202                        Lovef->L[fr*(sh_nmax+1)+deg]=lovel;
     1203                        deleted_layer_offset=(matlitho->numlayers+1)*6-vars->nyi;// =6 per deleted layer
     1204                        kernel_index=fr*(sh_nmax+1)*(matlitho->numlayers+1)*6 + deg*(matlitho->numlayers+1)*6 + deleted_layer_offset;
     1205                        for (int i=0;i<vars->nyi;i++){
     1206                                Lovef->Kernels[kernel_index+i]=yi_righthandside[i];
     1207                        }
     1208                }
     1209        }
     1210
     1211        if (Elastic) { // if elastic values were provided, we copy elastic love numbers above the cutoff degree instead of calculating them
     1212                for(int deg=sh_cutoff+1;deg<sh_nmax+1;deg++){
     1213                        if (VerboseSolution() && Elastic  && verbosecpu) {
     1214                                if (deg==sh_nmax || deg%100==0) _printf_("\r   Degree: " << deg << "/" << Lovef->sh_nmax << "    ");
     1215                        }
     1216                        for (int fr=0;fr<nfreq;fr++){
     1217                                // just copy the elastic values
     1218                                Lovef->H[fr*(sh_nmax+1)+deg]=Elastic->H[deg];
     1219                                Lovef->K[fr*(sh_nmax+1)+deg]=Elastic->K[deg];
     1220                                Lovef->L[fr*(sh_nmax+1)+deg]=Elastic->L[deg];
     1221                                deleted_layer_offset=(matlitho->numlayers+1)*6-vars->nyi;// =6 per deleted layer
     1222                                kernel_index=fr*(sh_nmax+1)*(matlitho->numlayers+1)*6 + deg*(matlitho->numlayers+1)*6 + deleted_layer_offset;
     1223                                kernel_indexe=deg*(matlitho->numlayers+1)*6 + deleted_layer_offset;
     1224                                for (int i=0;i<vars->nyi;i++){
     1225                                        Lovef->Kernels[kernel_index+i]=Elastic->Kernels[kernel_indexe+i];
     1226                                }
     1227                        }
     1228                }
     1229        }
     1230
     1231        if (VerboseSolution() && Elastic  && verbosecpu) _printf_("\n");
     1232        xDelete<doubletype>(yi);
     1233        xDelete<doubletype>(yi_righthandside);
     1234        xDelete<doubletype>(yi_prefactor);
    9591235}/*}}}*/
    9601236
     
    9731249        IssmDouble  g0,r0;
    9741250        int         nyi,starting_layer;
     1251        int*        deg_layer_delete;
    9751252
    9761253        femmodel->parameters->FindParam(&GG,LoveGravitationalConstantEnum);
    9771254        EarthMass=xNewZeroInit<IssmDouble>(numlayers+1);
     1255        deg_layer_delete=xNewZeroInit<int>(numlayers);
    9781256
    9791257        for (int i=0;i<numlayers;i++){
     
    9931271        starting_layer=0;
    9941272
    995         return new LoveVariables(EarthMass,g0,r0,nyi,starting_layer);
     1273        if(VerboseSolution()){
     1274                _printf_("     Surface gravity: " << g0 << " m.s^-2\n");
     1275                _printf_("     Mean density: " << EarthMass[numlayers-1]/(4.0/3.0*PI*pow(r0,3.0)) << " kg.m^-3\n");
     1276        }
     1277
     1278        return new LoveVariables(EarthMass,g0,r0,nyi,starting_layer,deg_layer_delete);
    9961279
    9971280} /*}}}*/
     
    9991282
    10001283        Matlitho*   matlitho=NULL;
    1001         int         nfreq,nyi,starting_layer,nstep,forcing_type,dummy;
     1284        int         nfreq, NTit,nt, forcing_type,dummy, sh_cutoff;
    10021285        int         sh_nmin,sh_nmax,kernel_index,deleted_layer_offset;
    1003         bool        allow_layer_deletion,love_kernels, istemporal;
     1286        bool        allow_layer_deletion,love_kernels, istemporal, freq_skip;
    10041287        bool        verbosemod = (int)VerboseModule();
    1005         IssmDouble  mu0, underflow_tol;
    10061288        IssmDouble *frequencies = NULL;
     1289        IssmDouble *frequencies_local=NULL;
    10071290        bool        save_results;
    10081291        bool        complex_computation;
     1292        bool        verbosecpu=false;
    10091293
    10101294        doubletype  omega;
    10111295        doubletype  lovek, loveh, lovel, loveratio;
    1012 
    1013         doubletype*  LoveKf = NULL;
    1014         doubletype*  LoveHf = NULL;
    1015         doubletype*  LoveLf = NULL;
    1016 
    1017         doubletype*  LoveKernels= NULL;
     1296        IssmDouble pw_threshold, pw_test_h, pw_test_l,pw_test_k;
     1297
     1298        LoveNumbers<doubletype>* Lovef=NULL;
     1299        LoveNumbers<doubletype>* Tidalf=NULL;
     1300
     1301        /* parallel computing */
     1302        LoveNumbers<doubletype>* Lovef_local=NULL;
     1303        LoveNumbers<doubletype>* Tidalf_local=NULL;
     1304
     1305        /*elastic & fluid love numbers*/
     1306        LoveNumbers<doubletype>* Elastic=NULL;
     1307        IssmDouble* frequencies_elastic=NULL;
     1308        LoveNumbers<doubletype>* Fluid=NULL;
     1309        IssmDouble* frequencies_fluid=NULL;
     1310
    10181311        LoveVariables* vars=NULL;
    1019         doubletype* yi_prefactor=NULL;
    1020         doubletype* yi_righthandside=NULL;
    1021         doubletype* yi=NULL;
    1022 
    1023         if(VerboseSolution()) _printf0_("   computing LOVE numbers\n");
    10241312
    10251313        /*recover materials parameters: there is only one Matlitho, chase it down the hard way:*/
     
    10391327        femmodel->parameters->FindParam(&sh_nmax,LoveShNmaxEnum);
    10401328        femmodel->parameters->FindParam(&sh_nmin,LoveShNminEnum);
    1041         femmodel->parameters->FindParam(&mu0,LoveMu0Enum);
    10421329        femmodel->parameters->FindParam(&allow_layer_deletion,LoveAllowLayerDeletionEnum);
    10431330        femmodel->parameters->FindParam(&love_kernels,LoveKernelsEnum);
    10441331        femmodel->parameters->FindParam(&forcing_type,LoveForcingTypeEnum);
    10451332        femmodel->parameters->FindParam(&istemporal,LoveIsTemporalEnum);
    1046         femmodel->parameters->FindParam(&nstep,LoveIntStepsPerLayerEnum);
    10471333        femmodel->parameters->FindParam(&complex_computation,LoveComplexComputationEnum);
    1048 
    1049         /*Initialize three love matrices: geoid, vertical and horizontal displacement (real and imaginary parts) */
    1050         LoveKf = xNewZeroInit<doubletype>(nfreq*(sh_nmax+1));
    1051         LoveHf = xNewZeroInit<doubletype>(nfreq*(sh_nmax+1));
    1052         LoveLf = xNewZeroInit<doubletype>(nfreq*(sh_nmax+1));
     1334        femmodel->parameters->FindParam(&pw_threshold,LovePostWidderThresholdEnum);
     1335        if (istemporal) femmodel->parameters->FindParam(&NTit,LoveNTemporalIterationsEnum);
     1336
     1337        /*Initialize three love matrices: geoid, vertical and horizontal displacement*/
     1338        Lovef= new LoveNumbers<doubletype>(sh_nmin,sh_nmax,nfreq, matlitho);
     1339        Tidalf= new LoveNumbers<doubletype>(2,2,nfreq, matlitho);
     1340        Elastic= new LoveNumbers<doubletype>(sh_nmin,sh_nmax,1,matlitho);
     1341        Fluid= new LoveNumbers<doubletype>(sh_nmin,sh_nmax,1,matlitho);
    10531342
    10541343        /*Initialize love kernels (real and imaginary parts): */
    1055         LoveKernels= xNewZeroInit<doubletype>(nfreq*(sh_nmax+1)*(matlitho->numlayers+1)*6);
    1056 
    10571344        vars=love_init(femmodel,matlitho);
    10581345
    1059         yi_prefactor=xNewZeroInit<doubletype>(6*6*nstep*matlitho->numlayers);
    1060         yi_righthandside=xNewZeroInit<doubletype>(vars->nyi);
    1061         yi=xNewZeroInit<doubletype>(vars->nyi*vars->nyi);
    1062 
    1063         //precalculate yi coefficients that do not depend on degree or frequency
    1064         fill_yi_prefactor<doubletype>(yi_prefactor, NULL, NULL,femmodel, matlitho,vars);
    1065         for(int deg=sh_nmin;deg<sh_nmax+1;deg++){
    1066 
    1067                 //precalculate yi coefficients that depend on degree but not frequency
    1068                 fill_yi_prefactor<doubletype>(yi_prefactor, &deg, NULL,femmodel, matlitho,vars);
    1069 
    1070                 for (int fr=0;fr<nfreq;fr++){
    1071                         omega=angular_frequency<doubletype>(frequencies[fr]);
    1072 
    1073                         //precalculate yi coefficients that depend on degree and frequency
    1074                         fill_yi_prefactor<doubletype>(yi_prefactor, &deg,&omega,femmodel, matlitho,vars);
    1075 
    1076                         yi_boundary_conditions<doubletype>(yi_righthandside,deg,femmodel,matlitho,vars);
    1077 
    1078                         build_yi_system<doubletype>(yi,deg,omega,yi_prefactor,femmodel,matlitho,vars);
    1079 
    1080                         solve_yi_system<doubletype>(&loveh,&lovel,&lovek, deg, omega, yi, yi_righthandside,femmodel, matlitho,vars);
    1081 
    1082                         LoveHf[deg*nfreq+fr]=loveh;
    1083                         LoveKf[deg*nfreq+fr]=lovek-1.0;
    1084                         LoveLf[deg*nfreq+fr]=lovel;
    1085 
    1086                         deleted_layer_offset=(matlitho->numlayers+1)*6-vars->nyi;// =6 per deleted layer
    1087                         kernel_index=deg*nfreq*(matlitho->numlayers+1)*6 + fr*(matlitho->numlayers+1)*6 + deleted_layer_offset;
    1088                         for (int i=0;i<vars->nyi;i++){
    1089                                 LoveKernels[kernel_index+i]=yi_righthandside[i];
    1090                         }
    1091                 }
    1092         }
    1093 
    1094         xDelete<doubletype>(yi);
    1095         xDelete<doubletype>(yi_righthandside);
     1346        //distribute frequencies for parallel computation /*{{{*/
     1347        int nt_local, nf_local, lower_row, upper_row;
     1348        if (istemporal){
     1349                //temporal love numbers are obtained via blocks of 2*NTit frequencies samples
     1350                //here we are making sure no block is split between different cpus, which would make the inverse laplace transform impossible
     1351                nt=nfreq/2/NTit;
     1352                nt_local=DetermineLocalSize(nt,IssmComm::GetComm());
     1353                nf_local=nt_local*2*NTit; // number of local frequencies
     1354                GetOwnershipBoundariesFromRange(&lower_row,&upper_row,nt_local,IssmComm::GetComm());
     1355                lower_row*=2*NTit;
     1356                upper_row*=2*NTit;
     1357        }
     1358        else{
     1359                //in this case frequency samples are completely independent so we can split them evenly across cpus
     1360                nf_local=DetermineLocalSize(nfreq,IssmComm::GetComm());
     1361                GetOwnershipBoundariesFromRange(&lower_row,&upper_row,nf_local,IssmComm::GetComm());
     1362        }
     1363
     1364        if (lower_row==0) verbosecpu=true; //let only cpu1 be verbose
     1365        if(VerboseSolution() && verbosecpu) _printf0_("   computing LOVE numbers\n");
     1366
     1367        frequencies_local=xNewZeroInit<IssmDouble>(nf_local);
     1368        for (int fr=0;fr<nf_local;fr++) frequencies_local[fr]=frequencies[lower_row+fr];
     1369
     1370        Lovef_local= new LoveNumbers<doubletype>(sh_nmin,sh_nmax,nf_local, matlitho);
     1371        Tidalf_local= new LoveNumbers<doubletype>(2,2,nf_local, matlitho);
     1372
     1373        /*}}}*/
     1374        frequencies_elastic=xNewZeroInit<IssmDouble>(1);
     1375        frequencies_fluid=xNewZeroInit<IssmDouble>(1);
     1376        for (int fr=0;fr<nfreq;fr++){ // find the lowest non-zero frequency requested
     1377                if (frequencies_fluid[0]==0) frequencies_fluid[0]=frequencies[fr];
     1378                else if(frequencies[fr]!=0 && frequencies_fluid[0]>frequencies[fr]) frequencies_fluid[0]=frequencies[fr];
     1379        }
     1380
     1381        // run elastic and fluid love numbers
     1382        if(VerboseSolution() && verbosecpu) _printf_("     elastic\n");
     1383        compute_love_numbers<doubletype>(Elastic, NULL, forcing_type, sh_nmax,frequencies_elastic, femmodel, matlitho, vars,verbosecpu);
     1384
     1385        if (nfreq>1){
     1386                compute_love_numbers<doubletype>(Fluid, NULL, forcing_type, sh_nmax,frequencies_fluid, femmodel, matlitho, vars,verbosecpu);
     1387                sh_cutoff=sh_nmax;
     1388                for (int deg=100;deg<sh_nmax+1;deg++){
     1389                        pw_test_h=abs((Fluid->H[deg]-Elastic->H[deg])/Elastic->H[deg]);
     1390                        pw_test_k=abs((Fluid->K[deg]-Elastic->K[deg])/Elastic->K[deg]);
     1391                        pw_test_l=abs((Fluid->L[deg]-Elastic->L[deg])/Elastic->L[deg]);
     1392                        if (pw_test_h<pw_threshold && pw_test_k<pw_threshold && pw_test_l<pw_threshold){
     1393                                sh_cutoff=deg;
     1394                                if(VerboseSolution() && verbosecpu){
     1395                                        _printf_("   Degree: " << deg << "/" << sh_nmax << "    ");
     1396                                        _printf_("      found negligible variation across frequencies, will copy elastic values after this degree\n");
     1397                                        _printf_("      Delta_h/h=" << pw_test_h << "; Delta_k/k="<< pw_test_k << "; Delta_l/l=" << pw_test_l << "; threshold set to " << pw_threshold << "\n");
     1398                                }
     1399                                break;
     1400                        }
     1401                }
     1402        }
     1403        else sh_cutoff=sh_nmax;
     1404               
     1405
     1406
     1407        //Take care of rotationnal feedback love numbers first, if relevant /*{{{*/
     1408        if (forcing_type==11 && sh_nmin<=2 && sh_nmax>=2){ // if forcing is surface loading and we have degree 2
     1409                if(VerboseSolution() && verbosecpu) _printf_("     tidal\n");
     1410                int tidal_forcing_type=9;
     1411                compute_love_numbers<doubletype>(Tidalf_local, NULL,tidal_forcing_type=9, 2,frequencies_local, femmodel, matlitho, vars,verbosecpu);
     1412        }
     1413        /*}}}*/
     1414
     1415        //Resume requested forcing_type
     1416        if (nfreq>1){ // if we are not running just elastic love numbers
     1417                if(VerboseSolution() && verbosecpu){
     1418                        if (forcing_type==11) _printf_("     loading\n");
     1419                        else if(forcing_type==9) _printf_("     tidal\n");
     1420                        else _printf_("     love\n");
     1421                }
     1422                compute_love_numbers<doubletype>(Lovef_local, Elastic, forcing_type, sh_cutoff, frequencies_local, femmodel, matlitho, vars,verbosecpu);
     1423        }
     1424        else{
     1425                Lovef_local->Copy(Elastic);
     1426        }
     1427        /*}}}*/
     1428
    10961429
    10971430        //Temporal love numbers
    10981431        if (istemporal && !complex_computation){
    1099 
    1100                 IssmDouble*  LoveHtDouble=NULL;
    1101                 IssmDouble*  LoveKtDouble=NULL;
    1102                 IssmDouble*  LoveLtDouble=NULL;
    1103                 doubletype*  LoveHt=NULL;
    1104                 doubletype*  LoveLt=NULL;
    1105                 doubletype*  LoveKt=NULL;
    1106 
    1107                 int NTit;
    1108                 femmodel->parameters->FindParam(&NTit,LoveNTemporalIterationsEnum);
    1109                 int nt = nfreq/2/NTit;
    1110 
    1111                 LoveHt=xNewZeroInit<doubletype>((sh_nmax+1)*nt);
    1112                 LoveLt=xNewZeroInit<doubletype>((sh_nmax+1)*nt);
    1113                 LoveKt=xNewZeroInit<doubletype>((sh_nmax+1)*nt);
    1114 
    1115                 love_freq_to_temporal<doubletype>(LoveHt,LoveLt,LoveKt,LoveHf,LoveLf,LoveKf,femmodel);
    1116 
    1117                 /*Downcast and add into parameters:*/
    1118                 LoveHtDouble=xNew<IssmDouble>((sh_nmax+1)*nt);
    1119                 LoveLtDouble=xNew<IssmDouble>((sh_nmax+1)*nt);
    1120                 LoveKtDouble=xNew<IssmDouble>((sh_nmax+1)*nt);
    1121                 for(int i=0;i<(sh_nmax+1)*nt;i++){
    1122                         LoveHtDouble[i]=std::real(LoveHt[i]);
    1123                         LoveLtDouble[i]=std::real(LoveLt[i]);
    1124                         LoveKtDouble[i]=std::real(LoveKt[i]);
    1125                 }
     1432                /*Initialize*/
     1433                doubletype*  pmtf_colineart=NULL;
     1434                doubletype*  pmtf_orthot=NULL;
     1435                LoveNumbers<doubletype>* Lovet=NULL;
     1436                LoveNumbers<doubletype>* Tidalt=NULL;
     1437                /*Downcast arrays to be exported in parameters*/
     1438                LoveNumbers<IssmDouble>* LovetDouble=NULL;
     1439                LoveNumbers<IssmDouble>* TidaltDouble=NULL;
     1440                IssmDouble*  pmtf_colineartDouble=NULL;
     1441                IssmDouble*  pmtf_orthotDouble=NULL;
     1442                /* parallel computing */
     1443                doubletype*  pmtf_colineart_local=NULL;
     1444                doubletype*  pmtf_orthot_local=NULL;   
     1445                LoveNumbers<doubletype>* Lovet_local=NULL;
     1446                LoveNumbers<doubletype>* Tidalt_local=NULL;     
     1447
     1448                Lovet= new LoveNumbers<doubletype>(sh_nmin,sh_nmax,nt,matlitho);
     1449                Tidalt= new LoveNumbers<doubletype>(2,2,nt,matlitho);
     1450                pmtf_colineart=xNewZeroInit<doubletype>(3*nt);
     1451                pmtf_orthot=xNewZeroInit<doubletype>(3*nt);     
     1452
     1453                Lovet_local= new LoveNumbers<doubletype>(sh_nmin,sh_nmax,nt_local,matlitho);
     1454                Tidalt_local= new LoveNumbers<doubletype>(2,2,nt_local,matlitho);       
     1455                pmtf_colineart_local=xNewZeroInit<doubletype>(3*nt_local);
     1456                pmtf_orthot_local=xNewZeroInit<doubletype>(3*nt_local);
     1457
     1458                love_freq_to_temporal<doubletype>(Lovet_local,Tidalt_local,pmtf_colineart_local,pmtf_orthot_local,Lovef_local,Tidalf_local,frequencies_local,femmodel,verbosecpu);
     1459
     1460                /* MPI Gather */ /*{{{*/
     1461                Lovef->LoveMPI_Gather(Lovef_local, lower_row);
     1462                if (forcing_type==11 && sh_nmin<=2 && sh_nmax>=2){
     1463                        Tidalf->LoveMPI_Gather(Tidalf_local, lower_row);               
     1464                }
     1465                Lovet->LoveMPI_Gather(Lovet_local, lower_row/2/NTit);
     1466                Tidalt->LoveMPI_Gather(Tidalt_local, lower_row/2/NTit);
     1467                //pmtf:
     1468                int* recvcounts=xNew<int>(IssmComm::GetSize());
     1469                int* displs=xNew<int>(IssmComm::GetSize());
     1470                int  rc;
     1471                int  offset;
     1472                rc=3*nt_local;
     1473                offset=3*lower_row/2/NTit;
     1474                ISSM_MPI_Allgather(&rc,1,ISSM_MPI_INT,recvcounts,1,ISSM_MPI_INT,IssmComm::GetComm());
     1475                ISSM_MPI_Allgather(&offset,1,ISSM_MPI_INT,displs,1,ISSM_MPI_INT,IssmComm::GetComm());
     1476                ISSM_MPI_Allgatherv(pmtf_colineart_local, rc, ISSM_MPI_DOUBLE, pmtf_colineart, recvcounts, displs, ISSM_MPI_DOUBLE,IssmComm::GetComm());
     1477                ISSM_MPI_Allgatherv(pmtf_orthot_local, rc, ISSM_MPI_DOUBLE, pmtf_orthot, recvcounts, displs, ISSM_MPI_DOUBLE,IssmComm::GetComm());
     1478                xDelete<int>(recvcounts);
     1479                xDelete<int>(displs);
     1480                /*}}}*/
     1481
     1482                /*Downcast and add into parameters:*/ /*{{{*/
     1483                LovetDouble= new LoveNumbers<IssmDouble>(sh_nmin,sh_nmax,nt,matlitho);
     1484                TidaltDouble= new LoveNumbers<IssmDouble>(2,2,nt,matlitho);     
     1485
     1486                pmtf_colineartDouble=xNew<IssmDouble>(nt);
     1487                pmtf_orthotDouble=xNew<IssmDouble>(nt);
     1488
     1489                Lovet->DownCastToDouble(LovetDouble);
     1490                Tidalt->DownCastToDouble(TidaltDouble);
     1491                for(int i=0;i<nt;i++){
     1492                        pmtf_colineartDouble[i]=std::real(pmtf_colineart[2*nt+i]);
     1493                        pmtf_orthotDouble[i]=std::real(pmtf_orthot[2*nt+i]);
     1494                }
     1495
    11261496                if(forcing_type==9){ //tidal loading
    1127                         femmodel->parameters->AddObject(new DoubleMatParam(TidalLoveHEnum,LoveHtDouble,(sh_nmax+1)*nt,1));
    1128                         femmodel->parameters->AddObject(new DoubleMatParam(TidalLoveKEnum,LoveKtDouble,(sh_nmax+1)*nt,1));
    1129                         femmodel->parameters->AddObject(new DoubleMatParam(TidalLoveLEnum,LoveLtDouble,(sh_nmax+1)*nt,1));
     1497                        femmodel->parameters->AddObject(new DoubleMatParam(TidalLoveHEnum,LovetDouble->H,(sh_nmax+1)*nt,1));
     1498                        femmodel->parameters->AddObject(new DoubleMatParam(TidalLoveKEnum,LovetDouble->K,(sh_nmax+1)*nt,1));
     1499                        femmodel->parameters->AddObject(new DoubleMatParam(TidalLoveLEnum,LovetDouble->L,(sh_nmax+1)*nt,1));
    11301500                }
    11311501                else if(forcing_type==11){ //surface loading
    1132                         femmodel->parameters->AddObject(new DoubleMatParam(LoadLoveHEnum,LoveHtDouble,(sh_nmax+1)*nt,1));
    1133                         femmodel->parameters->AddObject(new DoubleMatParam(LoadLoveKEnum,LoveKtDouble,(sh_nmax+1)*nt,1));
    1134                         femmodel->parameters->AddObject(new DoubleMatParam(LoadLoveLEnum,LoveLtDouble,(sh_nmax+1)*nt,1));
    1135                 }
    1136                 xDelete<IssmDouble>(LoveHtDouble);
    1137                 xDelete<IssmDouble>(LoveKtDouble);
    1138                 xDelete<IssmDouble>(LoveLtDouble);
    1139 
     1502                        femmodel->parameters->AddObject(new DoubleMatParam(LoadLoveHEnum,LovetDouble->H,(sh_nmax+1)*nt,1));
     1503                        femmodel->parameters->AddObject(new DoubleMatParam(LoadLoveKEnum,LovetDouble->K,(sh_nmax+1)*nt,1));
     1504                        femmodel->parameters->AddObject(new DoubleMatParam(LoadLoveLEnum,LovetDouble->L,(sh_nmax+1)*nt,1));
     1505                        femmodel->parameters->AddObject(new DoubleMatParam(TidalLoveHEnum,TidaltDouble->H,3*nt,1));
     1506                        femmodel->parameters->AddObject(new DoubleMatParam(TidalLoveKEnum,TidaltDouble->K,3*nt,1));
     1507                        femmodel->parameters->AddObject(new DoubleMatParam(TidalLoveLEnum,TidaltDouble->L,3*nt,1));
     1508                        femmodel->parameters->AddObject(new DoubleMatParam(LovePolarMotionTransferFunctionColinearEnum,pmtf_colineartDouble,nt,1));
     1509                        femmodel->parameters->AddObject(new DoubleMatParam(LovePolarMotionTransferFunctionOrthogonalEnum,pmtf_orthotDouble,nt,1));
     1510                }
     1511
     1512                xDelete<IssmDouble>(pmtf_colineartDouble);
     1513                xDelete<IssmDouble>(pmtf_orthotDouble);
     1514                /*}}}*/
     1515       
    11401516                /*Add into external results, no need to downcast, we can handle complexes/quad precision: */
    1141                 femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveKrEnum,LoveKt,sh_nmax+1,nt,0,0));
    1142                 femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveHrEnum,LoveHt,sh_nmax+1,nt,0,0));
    1143                 femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveLrEnum,LoveLt,sh_nmax+1,nt,0,0));
    1144 
    1145                 xDelete<doubletype>(LoveHt);
    1146                 xDelete<doubletype>(LoveLt);
    1147                 xDelete<doubletype>(LoveKt);
     1517                femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveKtEnum,Lovet->K,nt,sh_nmax+1,0,0));
     1518                femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveHtEnum,Lovet->H,nt,sh_nmax+1,0,0));
     1519                femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveLtEnum,Lovet->L,nt,sh_nmax+1,0,0));
     1520
     1521                femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveTidalKtEnum,Tidalt->K,nt,3,0,0));
     1522                femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveTidalHtEnum,Tidalt->H,nt,3,0,0));
     1523                femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveTidalLtEnum,Tidalt->L,nt,3,0,0));
     1524                femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LovePMTF1tEnum,pmtf_colineart,nt,3,0,0));
     1525                femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LovePMTF2tEnum,pmtf_orthot,nt,3,0,0));
     1526
     1527                delete Lovet;
     1528                delete Tidalt;
     1529                delete Lovet_local;
     1530                delete Tidalt_local;
     1531                delete LovetDouble;
     1532                delete TidaltDouble;
     1533
     1534                xDelete<doubletype>(pmtf_colineart);
     1535                xDelete<doubletype>(pmtf_orthot);
    11481536        }
    11491537        else{
    1150 
    1151                 IssmDouble*  LoveHfDouble=NULL;
    1152                 IssmDouble*  LoveKfDouble=NULL;
    1153                 IssmDouble*  LoveLfDouble=NULL;
     1538                LoveNumbers<IssmDouble>* LovefDouble=NULL;
     1539                LovefDouble= new LoveNumbers<IssmDouble>(sh_nmin,sh_nmax,nfreq,matlitho);
     1540
     1541                /*MPI_Gather*/
     1542                if (nfreq>1){
     1543                        Lovef->LoveMPI_Gather(Lovef_local, lower_row);
     1544                        if (forcing_type==11 && sh_nmin<=2 && sh_nmax>=2){
     1545                                Tidalf->LoveMPI_Gather(Tidalf_local, lower_row);               
     1546                        }
     1547                }
     1548                else{
     1549                        Lovef->Copy(Elastic);
     1550                        Tidalf->Copy(Tidalf_local);
     1551                }
    11541552
    11551553                /*Add into parameters:*/
    1156                 LoveHfDouble=xNew<IssmDouble>((sh_nmax+1)*nfreq);
    1157                 LoveLfDouble=xNew<IssmDouble>((sh_nmax+1)*nfreq);
    1158                 LoveKfDouble=xNew<IssmDouble>((sh_nmax+1)*nfreq);
    1159                 for(int i=0;i<(sh_nmax+1)*nfreq;i++){
    1160                         LoveHfDouble[i]=std::real(LoveHf[i]);
    1161                         LoveLfDouble[i]=std::real(LoveLf[i]);
    1162                         LoveKfDouble[i]=std::real(LoveKf[i]);
    1163                 }
     1554                Lovef->DownCastToDouble(LovefDouble);
    11641555                if(forcing_type==9){ //tidal loading
    1165                         femmodel->parameters->AddObject(new DoubleMatParam(TidalLoveHEnum,LoveHfDouble,(sh_nmax+1)*nfreq,1));
    1166                         femmodel->parameters->AddObject(new DoubleMatParam(TidalLoveKEnum,LoveKfDouble,(sh_nmax+1)*nfreq,1));
    1167                         femmodel->parameters->AddObject(new DoubleMatParam(TidalLoveLEnum,LoveLfDouble,(sh_nmax+1)*nfreq,1));
     1556                        femmodel->parameters->AddObject(new DoubleMatParam(TidalLoveHEnum,LovefDouble->H,(sh_nmax+1)*nfreq,1));
     1557                        femmodel->parameters->AddObject(new DoubleMatParam(TidalLoveKEnum,LovefDouble->K,(sh_nmax+1)*nfreq,1));
     1558                        femmodel->parameters->AddObject(new DoubleMatParam(TidalLoveLEnum,LovefDouble->L,(sh_nmax+1)*nfreq,1));
    11681559                }
    11691560                else if(forcing_type==11){ //surface loading
    1170                         femmodel->parameters->AddObject(new DoubleMatParam(LoadLoveHEnum,LoveHfDouble,(sh_nmax+1)*nfreq,1));
    1171                         femmodel->parameters->AddObject(new DoubleMatParam(LoadLoveKEnum,LoveKfDouble,(sh_nmax+1)*nfreq,1));
    1172                         femmodel->parameters->AddObject(new DoubleMatParam(LoadLoveLEnum,LoveLfDouble,(sh_nmax+1)*nfreq,1));
    1173                 }
    1174                 xDelete<IssmDouble>(LoveHfDouble);
    1175                 xDelete<IssmDouble>(LoveKfDouble);
    1176                 xDelete<IssmDouble>(LoveLfDouble);
     1561                        femmodel->parameters->AddObject(new DoubleMatParam(LoadLoveHEnum,LovefDouble->H,(sh_nmax+1)*nfreq,1));
     1562                        femmodel->parameters->AddObject(new DoubleMatParam(LoadLoveKEnum,LovefDouble->K,(sh_nmax+1)*nfreq,1));
     1563                        femmodel->parameters->AddObject(new DoubleMatParam(LoadLoveLEnum,LovefDouble->L,(sh_nmax+1)*nfreq,1));
     1564                }
     1565                delete LovefDouble;
    11771566        }
    11781567
    11791568        /*Add into external results:*/
    1180         femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveKiEnum,LoveKf,sh_nmax+1,nfreq,0,0));
    1181         femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveHiEnum,LoveHf,sh_nmax+1,nfreq,0,0));
    1182         femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveLiEnum,LoveLf,sh_nmax+1,nfreq,0,0));
    1183 
     1569        femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveKfEnum,Lovef->K,nfreq,sh_nmax+1,0,0));
     1570        femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveHfEnum,Lovef->H,nfreq,sh_nmax+1,0,0));
     1571        femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveLfEnum,Lovef->L,nfreq,sh_nmax+1,0,0));
    11841572        /*Only when love_kernels is on*/
    11851573        if (love_kernels==1) {
    1186                 femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveKernelsEnum,LoveKernels,(sh_nmax+1)*(matlitho->numlayers+1)*6,nfreq,0,0));
    1187         }
    1188 
     1574                femmodel->results->AddObject(new GenericExternalResult<doubletype*>(femmodel->results->Size()+1,LoveKernelsEnum,Lovef->Kernels,nfreq,(sh_nmax+1)*(matlitho->numlayers+1)*6,0,0));
     1575        }
    11891576        /*Free resources:*/
    11901577        xDelete<IssmDouble>(frequencies);
    1191         xDelete<doubletype>(LoveKf);
    1192         xDelete<doubletype>(LoveHf);
    1193         xDelete<doubletype>(LoveLf);
    1194         xDelete<doubletype>(LoveKernels);
    1195 
     1578        xDelete<IssmDouble>(frequencies_local);
     1579        xDelete<IssmDouble>(frequencies_elastic);
     1580        delete Lovef;
     1581        delete Lovef_local;
     1582        delete Tidalf;
     1583        delete Tidalf_local;
     1584        delete Elastic;
    11961585        /* Legacy for fortran core, to be removed after complete validation */
    11971586
     
    12251614
    12261615        /*Add love matrices to results:*/
    1227         //femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveKrEnum,LoveKr,sh_nmax+1,nfreq,0,0));
    1228         //femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveHrEnum,LoveHr,sh_nmax+1,nfreq,0,0));
    1229         //femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveLrEnum,LoveLr,sh_nmax+1,nfreq,0,0));
    1230         //femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveKiEnum,LoveKi,sh_nmax+1,nfreq,0,0));
    1231         //femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveHiEnum,LoveHi,sh_nmax+1,nfreq,0,0));
    1232         //femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveLiEnum,LoveLi,sh_nmax+1,nfreq,0,0));
     1616        //femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveKtEnum,LoveKr,sh_nmax+1,nfreq,0,0));
     1617        //femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveHtEnum,LoveHr,sh_nmax+1,nfreq,0,0));
     1618        //femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveLtEnum,LoveLr,sh_nmax+1,nfreq,0,0));
     1619        //femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveKfEnum,LoveKi,sh_nmax+1,nfreq,0,0));
     1620        //femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveHfEnum,LoveHi,sh_nmax+1,nfreq,0,0));
     1621        //femmodel->results->AddObject(new GenericExternalResult<IssmDouble*>(femmodel->results->Size()+1,LoveLfEnum,LoveLi,sh_nmax+1,nfreq,0,0));
    12331622
    12341623        //xDelete<IssmDouble>(LoveKr);
     
    12511640template void        GetEarthRheology<IssmDouble>(IssmDouble* pla, IssmDouble* pmu, int layer_index, IssmDouble omega,  Matlitho* matlitho);
    12521641template void        GetEarthRheology<IssmComplex>(IssmComplex* pla, IssmComplex* pmu, int layer_index, IssmComplex omega,  Matlitho* matlitho);
    1253 template void        yi_boundary_conditions<IssmDouble>(IssmDouble* yi_righthandside, int deg, FemModel* femmodel, Matlitho* matlitho,LoveVariables* vars);
    1254 template void        yi_boundary_conditions<IssmComplex>(IssmComplex* yi_righthandside, int deg, FemModel* femmodel, Matlitho* matlitho,LoveVariables* vars);
     1642template void        yi_boundary_conditions<IssmDouble>(IssmDouble* yi_righthandside, int deg, FemModel* femmodel, Matlitho* matlitho,LoveVariables* vars, int forcing_type);
     1643template void        yi_boundary_conditions<IssmComplex>(IssmComplex* yi_righthandside, int deg, FemModel* femmodel, Matlitho* matlitho,LoveVariables* vars, int forcing_type);
    12551644template void        yi_derivatives<IssmDouble>(IssmDouble* dydx, IssmDouble* y, int layer_index, int n, IssmDouble* yi_prefactor, FemModel* femmodel, Matlitho* matlitho);
    12561645template void        yi_derivatives<IssmComplex>(IssmComplex* dydx, IssmComplex* y, int layer_index, int n, IssmComplex* yi_prefactor, FemModel* femmodel, Matlitho* matlitho);
     
    12631652template void        build_yi_system<IssmDouble>(IssmDouble* yi, int deg, IssmDouble omega, IssmDouble* yi_prefactor, FemModel* femmodel, Matlitho* matlitho,LoveVariables* vars);
    12641653template void        build_yi_system<IssmComplex>(IssmComplex* yi, int deg, IssmComplex omega, IssmComplex* yi_prefactor, FemModel* femmodel, Matlitho* matlitho,LoveVariables* vars);
    1265 template void        solve_yi_system<IssmDouble>(IssmDouble* loveh, IssmDouble* lovel, IssmDouble* lovek, int deg, IssmDouble omega, IssmDouble* yi, IssmDouble* rhs, FemModel* femmodel, Matlitho* matlitho, LoveVariables* vars);
    1266 template void        solve_yi_system<IssmComplex>(IssmComplex* loveh, IssmComplex* lovel, IssmComplex* lovek, int deg, IssmComplex omega, IssmComplex* yi, IssmComplex* rhs, FemModel* femmodel, Matlitho* matlitho, LoveVariables* vars);
     1654template void        solve_yi_system<IssmDouble>(IssmDouble* loveh, IssmDouble* lovel, IssmDouble* lovek, int deg, IssmDouble omega, IssmDouble* frequencies, IssmDouble* yi, IssmDouble* rhs, FemModel* femmodel, Matlitho* matlitho, LoveVariables* vars,bool verbosecpu);
     1655template void        solve_yi_system<IssmComplex>(IssmComplex* loveh, IssmComplex* lovel, IssmComplex* lovek, int deg, IssmComplex omega, IssmDouble* frequencies, IssmComplex* yi, IssmComplex* rhs, FemModel* femmodel, Matlitho* matlitho, LoveVariables* vars,bool verbosecpu);
     1656template void        compute_love_numbers<IssmDouble>(LoveNumbers<IssmDouble>* Lovef, LoveNumbers<IssmDouble>* Elastic, int forcing_type, int sh_cutoff,IssmDouble* frequencies, FemModel* femmodel, Matlitho* matlitho, LoveVariables* vars, bool verbosecpu);
     1657template void        compute_love_numbers<IssmComplex>(LoveNumbers<IssmComplex>* Lovef, LoveNumbers<IssmComplex>* Elastic, int forcing_type, int sh_cutoff, IssmDouble* frequencies, FemModel* femmodel, Matlitho* matlitho, LoveVariables* vars, bool verbosecpu);
    12671658template IssmDouble  factorial<IssmDouble>(int n);
    12681659template IssmDouble* postwidder_coef<IssmDouble>(int NTit);
    12691660template IssmDouble  n_C_r<IssmDouble>(int n, int r);
    1270 template void         postwidder_transform<IssmDouble>(IssmDouble* Lovet, IssmDouble* Lovef,int d, int t, int NTit, IssmDouble* xi, FemModel* femmodel);
     1661template void         postwidder_transform<IssmDouble>(IssmDouble* Lovet, IssmDouble* Lovef,int d, int t, int sh_nmax,int NTit, IssmDouble* xi, FemModel* femmodel);
    12711662
    12721663/*}}}*/
  • issm/trunk/src/c/cores/masstransport_core.cpp

    r26744 r27035  
    4949                solutionsequence_linear(femmodel);
    5050                femmodel->parameters->SetParam(SurfaceEnum,InputToExtrudeEnum);
     51                extrudefromtop_core(femmodel);
     52                femmodel->parameters->SetParam(ThicknessEnum,InputToExtrudeEnum);
     53                extrudefromtop_core(femmodel);
     54                femmodel->parameters->SetParam(BaseEnum,InputToExtrudeEnum);
    5155                extrudefromtop_core(femmodel);
    5256        }
  • issm/trunk/src/c/cores/movingfront_core.cpp

    r26744 r27035  
    4848        }
    4949
     50        /* smoothen slope of lsf for computation of normal on ice domain*/
     51        levelsetfunctionslope_core(femmodel);
     52
    5053        /* start the work from here */
    5154        if(VerboseSolution()) _printf0_("   computing calving and undercutting\n");
     
    5356        FrontalForcingsx(femmodel);
    5457        if(VerboseSolution()) _printf0_("   computing new ice front position\n");
    55 
    56         /* smoothen slope of lsf for computation of normal on ice domain*/
    57         levelsetfunctionslope_core(femmodel);
    5858
    5959        /* determine variables for extrapolation */
     
    114114
    115115        /* solve level set equation */
    116         analysis = new LevelsetAnalysis();
    117         analysis->Core(femmodel);
    118         delete analysis;
     116        LevelsetAnalysis lsanalysis;
     117        lsanalysis.Core(femmodel);
     118        lsanalysis.PostProcess(femmodel);
    119119
    120120        /*Kill ice berg to avoid free body motion*/
    121121        if(killicebergs){
     122                int killberg = 0;
    122123                if(VerboseSolution()) _printf0_("   looking for icebergs to kill\n");
    123                 KillIcebergsx(femmodel);
     124                killberg = KillIcebergsx(femmodel);
     125                /*wait for all cores*/
     126                int totalkill;
     127                ISSM_MPI_Reduce(&killberg,&totalkill,1,ISSM_MPI_INT,ISSM_MPI_SUM,0,IssmComm::GetComm());
     128                ISSM_MPI_Bcast(&totalkill,1,ISSM_MPI_INT,0,IssmComm::GetComm());
     129
     130                if (totalkill > 0) {
     131                        if(VerboseSolution()) _printf0_("   reinitializing level set after killing " << totalkill << " icebergs\n");
     132                        femmodel->ResetLevelset();
     133                        ResetBoundaryConditions(femmodel,LevelsetAnalysisEnum);
     134                }
    124135        }
    125136
     
    128139                if(VerboseSolution()) _printf0_("   reinitializing level set\n");
    129140                femmodel->ResetLevelset();
     141                ResetBoundaryConditions(femmodel,LevelsetAnalysisEnum);
    130142        }
    131143
     
    133145        GetMaskOfIceVerticesLSMx(femmodel);
    134146
     147        /*Save results*/
     148        if(save_results){
     149                int outputs[1] = {MaskIceLevelsetEnum};
     150                femmodel->RequestedOutputsx(&femmodel->results,&outputs[0],1);
     151        }
     152
    135153        /*End profiler*/
    136154        femmodel->profiler->Stop(MOVINGFRONTCORE);
  • issm/trunk/src/c/cores/sampling_core.cpp

    r26744 r27035  
    55#include "../classes/classes.h"
    66#include "../solutionsequences/solutionsequences.h"
     7#include "../analyses/analyses.h" // new
     8#include "../modules/modules.h"
    79
    810void sampling_core(FemModel* femmodel){
     
    3032        /*Generate random sample*/
    3133        if(VerboseSolution()) _printf0_("   call computational core\n");
     34        SamplingAnalysis* analysis = new SamplingAnalysis();
    3235        femmodel->SetCurrentConfiguration(SamplingAnalysisEnum);
     36
     37        if(solution_type==TransientSolutionEnum){
     38                InputDuplicatex(femmodel,SampleEnum,SampleOldEnum);
     39
     40    int seed;
     41                femmodel->parameters->FindParam(&seed,SamplingSeedEnum);
     42                if(seed>=0){
     43                        int step;
     44                        femmodel->parameters->FindParam(&step,StepEnum);
     45                        seed = seed + 13923272*step; // change default seed for transient simulations (by considering an arbitrary shift based on the step number)
     46                        femmodel->parameters->SetParam(seed,SamplingSeedEnum);
     47                }
     48
     49        }
     50
    3351        solutionsequence_sampling(femmodel);
     52
     53        if(solution_type==TransientSolutionEnum){
     54
     55                InputDuplicatex(femmodel,SampleEnum,SampleNoiseEnum);
     56
     57                analysis->UpdateTransientSample(femmodel);
     58
     59        }
     60
     61        delete analysis;
    3462
    3563        if(save_results){
     
    4674        /*profiler*/
    4775        femmodel->profiler->Stop(SAMPLINGCORE);
     76
     77
    4878}
  • issm/trunk/src/c/cores/sealevelchange_core.cpp

    r26744 r27035  
    2424bool slcconvergence(Vector<IssmDouble>* RSLg,Vector<IssmDouble>* RSLg_old,IssmDouble eps_rel,IssmDouble eps_abs);
    2525IssmDouble  SealevelloadsOceanAverage(GrdLoads* loads, Vector<IssmDouble>* oceanareas, Vector<IssmDouble>* subelementoceanareas, IssmDouble totaloceanarea);
    26 void PolarMotion(IssmDouble* m, FemModel* femmodel,GrdLoads* loads, SealevelGeometry* slgeom);
     26void PolarMotion(IssmDouble* m, FemModel* femmodel,GrdLoads* loads, SealevelGeometry* slgeom, bool computefuture);
     27void SealevelchangeUpdateViscousTimeSeries(FemModel* femmodel);
    2728void ConserveOceanMass(FemModel* femmodel,GrdLoads* loads, IssmDouble offset, SealevelGeometry* slgeom);
    2829void ivins_deformation_core(FemModel* femmodel);
     
    247248        bool rotation=false;
    248249        bool planethasocean=false;
     250        bool computefuture=false;
    249251        IssmDouble*           sealevelpercpu=NULL;
    250252
     
    304306        if(VerboseSolution()) _printf0_("         starting  GRD convolutions\n");
    305307
    306         /*update viscous RSL:*/
    307         for(Object* & object : femmodel->elements->objects){
    308                 Element* element = xDynamicCast<Element*>(object);
    309                 element->SealevelchangeUpdateViscousFields();
    310         }
     308        /*update viscous time series to keep up with time stepping:*/
     309        SealevelchangeUpdateViscousTimeSeries(femmodel);
    311310
    312311        /*buildup loads: */
     
    319318        loads->BroadcastLoads();
    320319
    321         //compute polar motion:
    322         PolarMotion(&polarmotionvector[0],femmodel,loads,slgeom);
    323 
    324320        /*skip computation of sea level equation if requested, which means sea level loads should be zeroed */
    325321        if(!sealevelloading){
    326322                loads->sealevelloads=xNewZeroInit<IssmDouble>(nel);
    327323                loads->subsealevelloads=xNewZeroInit<IssmDouble>(slgeom->nbar[SLGEOM_OCEAN]);
    328 
     324                PolarMotion(&polarmotionvector[0],femmodel,loads, slgeom, computefuture=true);
    329325                goto deformation;
    330326        }
     
    332328        if(VerboseSolution()) _printf0_("         converging GRD convolutions\n");
    333329        for(;;){
     330
     331                //compute polar motion:
     332                PolarMotion(&polarmotionvector[0],femmodel,loads,slgeom,computefuture=false);
    334333
    335334                oldsealevelloads=loads->vsealevelloads->Duplicate(); loads->vsealevelloads->Copy(oldsealevelloads);
     
    338337                for(Object* & object : femmodel->elements->objects){
    339338                        Element* element = xDynamicCast<Element*>(object);
    340                         element->SealevelchangeConvolution(sealevelpercpu, loads , polarmotionvector,slgeom);
     339                        element->SealevelchangeConvolution(sealevelpercpu, loads, polarmotionvector,slgeom);
    341340                }
    342341
     
    364363                loads->BroadcastSealevelLoads();
    365364
    366                 //compute polar motion:
    367                 PolarMotion(&polarmotionvector[0],femmodel,loads, slgeom);
    368 
    369365                //convergence?
    370366                if(slcconvergence(loads->vsealevelloads,oldsealevelloads,eps_rel,eps_abs))break;
     
    374370                iterations++;
    375371        }
     372
     373        //recompute polar motion one final time, this time updating viscous stacks for future time steps
     374        if (viscous)    PolarMotion(&polarmotionvector[0],femmodel,loads, slgeom, computefuture=true);
    376375
    377376        deformation:
     
    418417
    419418        if (rotation) {
    420                 femmodel->results->AddResult(new GenericExternalResult<IssmDouble>(femmodel->results->Size()+1,SealevelInertiaTensorXZEnum,polarmotionvector[0],step,time));
    421                 femmodel->results->AddResult(new GenericExternalResult<IssmDouble>(femmodel->results->Size()+1,SealevelInertiaTensorYZEnum,polarmotionvector[1],step,time));
    422                 femmodel->results->AddResult(new GenericExternalResult<IssmDouble>(femmodel->results->Size()+1,SealevelInertiaTensorZZEnum,polarmotionvector[2],step,time));
     419                femmodel->results->AddResult(new GenericExternalResult<IssmDouble>(femmodel->results->Size()+1,SealevelchangePolarMotionXEnum,polarmotionvector[0],step,time));
     420                femmodel->results->AddResult(new GenericExternalResult<IssmDouble>(femmodel->results->Size()+1,SealevelchangePolarMotionYEnum,polarmotionvector[1],step,time));
     421                femmodel->results->AddResult(new GenericExternalResult<IssmDouble>(femmodel->results->Size()+1,SealevelchangePolarMotionZEnum,polarmotionvector[2],step,time));
    423422        }
    424423
     
    666665        }
    667666
     667        /*Compute spherical harmonic functions for spatial integrations of the loads*/
     668        slgeom->BuildSphericalHarmonics();
     669
    668670        femmodel->parameters->AddObject(new DoubleVecParam(XxeEnum,xxe,nel));
    669671        femmodel->parameters->AddObject(new DoubleVecParam(YyeEnum,yye,nel));
     
    731733
    732734        vsealevelloadsvolume->PointwiseMult(loads->vsealevelloads,oceanareas);
    733         vsubsealevelloadsvolume->PointwiseMult(loads->vsubsealevelloads,suboceanareas);
     735        vsubsealevelloadsvolume->PointwiseMult(loads->vsubsealevelloads,suboceanareas); 
    734736
    735737        vsealevelloadsvolume->Sum(&sealevelloadsaverage);
     
    740742        return (sealevelloadsaverage+subsealevelloadsaverage)/totaloceanarea;
    741743} /*}}}*/
    742 void PolarMotion(IssmDouble* polarmotionvector, FemModel* femmodel,GrdLoads* loads, SealevelGeometry* slgeom){ /*{{{*/
    743 
    744         IssmDouble  moi_list[3]={0,0,0};
    745         IssmDouble  moi_list_sub[3]={0,0,0};
    746         IssmDouble  moi_list_cpu[3]={0,0,0};
    747         IssmDouble*     tide_love_h  = NULL;
    748         IssmDouble*     tide_love_k  = NULL;
    749         IssmDouble*     load_love_k  = NULL;
    750         IssmDouble  tide_love_k2secular;
    751         IssmDouble  moi_e, moi_p;
    752         IssmDouble      m1, m2, m3;
     744void PolarMotion(IssmDouble* polarmotionvector, FemModel* femmodel,GrdLoads* loads, SealevelGeometry* slgeom, bool computefuture){ /*{{{*/
     745        //The purpose of this routine is to get the polar motion vector m=(m1, m2, m3) induced by the GrdLoads
     746        IssmDouble  S2coef[3];
     747        IssmDouble*     pmtf_col= NULL;
     748        IssmDouble*     pmtf_ortho   = NULL;
     749        IssmDouble*     pmtf_z   = NULL;
     750        IssmDouble* m1=NULL;
     751        IssmDouble* m2=NULL;
     752        IssmDouble* m3=NULL;
     753        IssmDouble* m1interp=NULL;
     754        IssmDouble* m2interp=NULL;
     755        IssmDouble* m3interp=NULL;
     756
     757        IssmDouble  moi_e, moi_p, re;
     758        IssmDouble mhprefactor, mzprefactor;
    753759        bool rotation=false;
     760        bool viscous=false;
     761        int nt=1;
     762
     763        IssmDouble* viscoustimes=NULL;
     764        IssmDouble* viscouspolarmotion=NULL;
     765        int         viscousnumsteps;
     766        int         viscousindex=0;
     767        int         dummy;
     768        IssmDouble  currenttime, final_time, lincoeff, timeacc;
    754769
    755770        /*early return?:*/
     
    758773
    759774        /*retrieve parameters: */
    760         femmodel->parameters->FindParam(&load_love_k,NULL,NULL,LoadLoveKEnum);
    761         femmodel->parameters->FindParam(&tide_love_h,NULL,NULL,TidalLoveHEnum);
    762         femmodel->parameters->FindParam(&tide_love_k,NULL,NULL,TidalLoveKEnum);
    763         femmodel->parameters->FindParam(&tide_love_k2secular,TidalLoveK2SecularEnum);
     775        femmodel->parameters->FindParam(&viscous,SolidearthSettingsViscousEnum);
    764776        femmodel->parameters->FindParam(&moi_e,RotationalEquatorialMoiEnum);
    765777        femmodel->parameters->FindParam(&moi_p,RotationalPolarMoiEnum);
    766 
    767         for(Object* & object : femmodel->elements->objects){
    768                 Element* element = xDynamicCast<Element*>(object);
    769 
    770                 element->SealevelchangeMomentOfInertiaCentroid(&moi_list[0],loads,slgeom);
    771                 element->SealevelchangeMomentOfInertiaSubElement(&moi_list_sub[0],loads, slgeom);
    772 
    773                 moi_list_cpu[0] += moi_list[0]+moi_list_sub[0];
    774                 moi_list_cpu[1] += moi_list[1]+moi_list_sub[1];
    775                 moi_list_cpu[2] += moi_list[2]+moi_list_sub[2];
    776         }
    777 
    778         for (int i=0;i<3;i++) moi_list[i]=0;
    779 
    780         ISSM_MPI_Reduce (&moi_list_cpu[0],&moi_list[0],1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
    781         ISSM_MPI_Bcast(&moi_list[0],1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
    782 
    783         ISSM_MPI_Reduce (&moi_list_cpu[1],&moi_list[1],1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
    784         ISSM_MPI_Bcast(&moi_list[1],1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
    785 
    786         ISSM_MPI_Reduce (&moi_list_cpu[2],&moi_list[2],1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
    787         ISSM_MPI_Bcast(&moi_list[2],1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
    788 
    789         /*compute perturbation terms for angular velocity vector: */
    790         m1 = 1/(1-tide_love_k[2]/tide_love_k2secular) * (1+load_love_k[2])/(moi_p-moi_e) * moi_list[0];
    791         m2 = 1/(1-tide_love_k[2]/tide_love_k2secular) * (1+load_love_k[2])/(moi_p-moi_e) * moi_list[1];
    792         m3 = -(1+load_love_k[2])/moi_p * moi_list[2];   // term associated with fluid number (3-order-of-magnitude smaller) is negelected
     778        femmodel->parameters->FindParam(&pmtf_col,NULL,SealevelchangePolarMotionTransferFunctionColinearEnum);
     779        femmodel->parameters->FindParam(&pmtf_ortho,NULL,SealevelchangePolarMotionTransferFunctionOrthogonalEnum);
     780        femmodel->parameters->FindParam(&pmtf_z,NULL,SealevelchangePolarMotionTransferFunctionZEnum);
     781        femmodel->parameters->FindParam(&re,SolidearthPlanetRadiusEnum);
     782
     783        if (viscous){
     784                femmodel->parameters->FindParam(&final_time,TimesteppingFinalTimeEnum);
     785                femmodel->parameters->FindParam(&timeacc,SolidearthSettingsTimeAccEnum);
     786                femmodel->parameters->FindParam(&viscousnumsteps,SealevelchangeViscousNumStepsEnum);
     787                femmodel->parameters->FindParam(&viscoustimes,NULL,SealevelchangeViscousTimesEnum);
     788                femmodel->parameters->FindParam(&viscousindex,SealevelchangeViscousIndexEnum);
     789                femmodel->parameters->FindParam(&currenttime,TimeEnum);
     790                femmodel->parameters->FindParam(&viscouspolarmotion,NULL,NULL,SealevelchangeViscousPolarMotionEnum);
     791
     792                if (computefuture){
     793                        nt = viscousnumsteps;
     794                        m1interp=xNewZeroInit<IssmDouble>(nt);
     795                        m2interp=xNewZeroInit<IssmDouble>(nt);
     796                        m3interp=xNewZeroInit<IssmDouble>(nt);
     797                }
     798        }
     799
     800        m1=xNewZeroInit<IssmDouble>(nt);
     801        m2=xNewZeroInit<IssmDouble>(nt);
     802        m3=xNewZeroInit<IssmDouble>(nt);
     803
     804        //Isolate degree 2 load coefficients
     805        for (int i=0;i<3;i++) S2coef[i]=0;
     806        loads->SHDegree2Coefficients(&S2coef[0],femmodel,slgeom);
     807
     808        //compute present (& future) polar motion from present loads
     809        mhprefactor=-4.*M_PI/5.*pow(re,4.)/(moi_p-moi_e);
     810        mzprefactor=8.*M_PI/15.*pow(re,4.)/moi_p;
     811        for (int tprime=0;tprime<nt;tprime++){
     812                m1[tprime] = mhprefactor * (pmtf_col[tprime] * S2coef[1] + pmtf_ortho[tprime] * S2coef[2]); //x-component
     813                m2[tprime] = mhprefactor * (pmtf_col[tprime] * S2coef[2] - pmtf_ortho[tprime] * S2coef[1]); //y-component
     814                m3[tprime] = mzprefactor *  pmtf_z[tprime]   * S2coef[0];                                   //z-component
     815        }
     816
     817        if(viscous){
     818                // we need to do up to 3 things (* = only if computefuture)
     819                // 1*: add new PM contribution to the viscous stack for future time steps
     820                // 2: collect viscous PM from past loads due at present-day and add it to PM[current_time]
     821                // 3*: subtract from viscous stack PM that has already been accounted for so we don't add it again at the next time step
     822                if(computefuture){
     823                        if(viscoustimes[viscousindex]<final_time){
     824                                lincoeff=(viscoustimes[viscousindex+1]-viscoustimes[viscousindex])/timeacc;
     825                                for(int t=viscousindex;t<nt;t++){ //we resynchronize m from the relative time above to the absolute time where t=0 <=> beginning of the simulation
     826                                        if(t==viscousindex){
     827                                                m1interp[t]=  m1[0];
     828                                                m2interp[t]=  m2[0];
     829                                                m3interp[t]=  m3[0];
     830                                        }
     831                                        else{ //we reinterpolate PM on viscoustimes, so we can handle the case where we are running with adaptative/uneven time steps
     832                                                int tprime=t-viscousindex-1;
     833                                                m1interp[t]=  (1.0-lincoeff)*m1[tprime]+lincoeff*m1[tprime+1];
     834                                                m2interp[t]=  (1.0-lincoeff)*m2[tprime]+lincoeff*m2[tprime+1];
     835                                                m3interp[t]=  (1.0-lincoeff)*m3[tprime]+lincoeff*m3[tprime+1];
     836                                        }
     837                                }
     838                        }
     839                }
     840                /*update PM at present time using viscous stack at present time: */
     841                m1[0]+=viscouspolarmotion[0*nt+viscousindex];
     842                m2[0]+=viscouspolarmotion[1*nt+viscousindex];
     843                m3[0]+=viscouspolarmotion[2*nt+viscousindex];
     844                if(computefuture){ /*update viscous stack with future deformation from present load: */
     845                        for(int t=nt-1;t>=viscousindex;t--){
     846                                //offset viscous PM to remove all deformation that has already been added
     847                                viscouspolarmotion[0*nt+t]+=m1interp[t]-m1interp[viscousindex]-viscouspolarmotion[0*nt+viscousindex];
     848                                viscouspolarmotion[1*nt+t]+=m2interp[t]-m2interp[viscousindex]-viscouspolarmotion[1*nt+viscousindex];
     849                                viscouspolarmotion[2*nt+t]+=m3interp[t]-m3interp[viscousindex]-viscouspolarmotion[2*nt+viscousindex];
     850                        }
     851                        // save updated viscous PM
     852                        femmodel->parameters->SetParam(viscouspolarmotion,viscousnumsteps,3,SealevelchangeViscousPolarMotionEnum);
     853                }
     854        }
     855       
    793856
    794857        /*Assign output pointers:*/
    795         polarmotionvector[0]=m1;
    796         polarmotionvector[1]=m2;
    797         polarmotionvector[2]=m3;
     858        polarmotionvector[0]=m1[0];
     859        polarmotionvector[1]=m2[0];
     860        polarmotionvector[2]=m3[0];
     861
     862        /*Free allocations:*/
     863        xDelete<IssmDouble>(m1);
     864        xDelete<IssmDouble>(m2);
     865        xDelete<IssmDouble>(m3);
     866        if (viscous){
     867                if (computefuture){
     868                        xDelete<IssmDouble>(m1interp);
     869                        xDelete<IssmDouble>(m2interp);
     870                        xDelete<IssmDouble>(m3interp);
     871                }
     872        }
     873
    798874} /*}}}*/
     875void       SealevelchangeUpdateViscousTimeSeries(FemModel* femmodel){ /*{{{*/
     876       
     877        IssmDouble* viscouspolarmotion=NULL;
     878        IssmDouble* viscoustimes=NULL;
     879        int         viscousnumsteps;
     880        int         viscousindex=0;
     881        int         newindex=0;
     882        int         dummy;
     883        bool        viscous=false;
     884        bool        rotation=false;
     885        IssmDouble  currenttime;
     886        IssmDouble  lincoeff=0;
     887               
     888        femmodel->parameters->FindParam(&viscous,SolidearthSettingsViscousEnum);
     889        femmodel->parameters->FindParam(&rotation,SolidearthSettingsRotationEnum);
     890       
     891        if(viscous){
     892                femmodel->parameters->FindParam(&viscousnumsteps,SealevelchangeViscousNumStepsEnum);
     893                femmodel->parameters->FindParam(&viscoustimes,NULL,SealevelchangeViscousTimesEnum);
     894                femmodel->parameters->FindParam(&viscousindex,SealevelchangeViscousIndexEnum);
     895                femmodel->parameters->FindParam(&currenttime,TimeEnum);
     896                if (rotation)   femmodel->parameters->FindParam(&viscouspolarmotion,NULL,NULL,SealevelchangeViscousPolarMotionEnum);
     897
     898                bool foundtime=false;
     899                int offset=1; //handles the egde case where time found = max time in viscoustimes
     900                lincoeff=0;
     901                newindex=viscousnumsteps-2;
     902
     903                for(int t=viscousindex;t<viscousnumsteps;t++){
     904                        if (viscoustimes[t]>=currenttime){
     905                                newindex=t-1;
     906                                foundtime=true;
     907                                lincoeff=(currenttime-viscoustimes[newindex])/(viscoustimes[t]-viscoustimes[newindex]);
     908                                offset=0;
     909                                break;
     910                        }
     911                }
     912
     913                if(rotation){
     914                        int index=0;
     915                        for (int i=0;i<3;i++){
     916                                index=i*viscousnumsteps+newindex;
     917                                viscouspolarmotion[index+offset]=(1-lincoeff)*viscouspolarmotion[index]+lincoeff*viscouspolarmotion[index+1];
     918                        }
     919                        femmodel->parameters->SetParam(viscouspolarmotion,viscousnumsteps,3,SealevelchangeViscousPolarMotionEnum);
     920                }
     921
     922
     923                /*update viscous inputs:*/
     924                for(Object* & object : femmodel->elements->objects){
     925                        Element* element = xDynamicCast<Element*>(object);
     926                        element->SealevelchangeUpdateViscousFields(lincoeff,newindex,offset);
     927                }
     928
     929                viscoustimes[newindex]=currenttime;
     930                viscousindex=newindex+offset;
     931
     932                femmodel->parameters->SetParam(viscousindex,SealevelchangeViscousIndexEnum);
     933                femmodel->parameters->SetParam(viscoustimes,viscousnumsteps,SealevelchangeViscousTimesEnum);
     934
     935                /*free allocations:*/
     936                xDelete<IssmDouble>(viscoustimes);
     937        }
     938
     939
     940}
    799941void        ConserveOceanMass(FemModel* femmodel,GrdLoads* loads, IssmDouble offset, SealevelGeometry* slgeom){ /*{{{*/
    800942
     
    809951IssmDouble* CombineLoads(IssmDouble* load,IssmDouble* subload,FemModel* femmodel, SealevelGeometry* slgeom,int loadtype,int nel){ /*{{{*/
    810952
     953        //merges loads on centroids and subelements onto a single variable loadcopy
    811954        int* indices=xNew<int>(nel);
    812955        for(int i=0;i<nel;i++)indices[i]=i;
  • issm/trunk/src/c/cores/stressbalance_core.cpp

    r26744 r27035  
    1919        bool       dakota_analysis,control_analysis;
    2020        int        domaintype;
    21         bool       isSIA,isSSA,isL1L2,isMLHO,isHO,isFS,isNitsche;
     21        bool       isSIA,isSSA,isL1L2,isMOLHO,isHO,isFS,isNitsche;
    2222        bool       save_results;
    2323        int        solution_type;
     
    3131        femmodel->parameters->FindParam(&isSSA,FlowequationIsSSAEnum);
    3232        femmodel->parameters->FindParam(&isL1L2,FlowequationIsL1L2Enum);
    33         femmodel->parameters->FindParam(&isMLHO,FlowequationIsMLHOEnum);
     33        femmodel->parameters->FindParam(&isMOLHO,FlowequationIsMOLHOEnum);
    3434        femmodel->parameters->FindParam(&isHO,FlowequationIsHOEnum);
    3535        femmodel->parameters->FindParam(&isFS,FlowequationIsFSEnum);
     
    7575
    7676        /*Compute stressbalance for SSA L1L2 HO and FS*/
    77         if(isSSA || isL1L2 || isMLHO || isHO || isFS){
     77        if(isSSA || isL1L2 || isMOLHO || isHO || isFS){
    7878                analysis = new StressbalanceAnalysis();
    7979                analysis->Core(femmodel);
     
    8282
    8383        /*Compute vertical velocities*/
    84         if (domaintype==Domain3DEnum && (isSIA || isSSA || isL1L2 || isMLHO || isHO)){
     84        if (domaintype==Domain3DEnum && (isSIA || isSSA || isL1L2 || isMOLHO || isHO)){
    8585
    8686                /*We need basal melt rates for vertical velocity*/
  • issm/trunk/src/c/cores/transient_core.cpp

    r26744 r27035  
    1616#include "../modules/modules.h"
    1717#include "../solutionsequences/solutionsequences.h"
     18
     19#ifdef _HAVE_CODIPACK_
     20extern CoDi_global codi_global;
     21#endif
    1822
    1923/*Prototypes*/
     
    7478                if(VerboseSolution()){
    7579                        _printf0_("iteration " << step << "/" << ceil((finaltime-time)/dt)+step << \
    76                                                 "  time [yr]: " << setprecision(4) << time/yts << " (time step: " << dt/yts << ")\n");
     80                                                "  time [yr]: " <<std::fixed<<setprecision(2)<< time/yts << " (time step: " << dt/yts << ")\n");
    7781                }
    7882                bool save_results=false;
     
    150154        femmodel->parameters->FindParam(&issampling,TransientIssamplingEnum);
    151155        femmodel->parameters->FindParam(&numoutputs,TransientNumRequestedOutputsEnum);
    152         femmodel->parameters->FindParam(&isstochasticforcing,StochasticForcingIsStochasticForcingEnum); 
     156        femmodel->parameters->FindParam(&isstochasticforcing,StochasticForcingIsStochasticForcingEnum);
    153157
    154158        #if defined(_HAVE_OCEAN_ )
     
    275279
    276280#ifdef _HAVE_CODIPACK_
    277 void transient_ad(FemModel* femmodel){/*{{{*/
     281double transient_ad(FemModel* femmodel, double* G, double* Jlist){/*{{{*/
    278282
    279283        /*parameters: */
     
    282286        bool       isoceancoupling;
    283287        int        step,timestepping;
    284         int        checkpoint_frequency;
     288        int        checkpoint_frequency,num_responses;
    285289
    286290        /*Get rank*/
     
    293297        femmodel->parameters->FindParam(&yts,ConstantsYtsEnum);
    294298        femmodel->parameters->FindParam(&timestepping,TimesteppingTypeEnum);
     299        femmodel->parameters->FindParam(&num_responses,InversionNumCostFunctionsEnum);
    295300        femmodel->parameters->FindParam(&checkpoint_frequency,SettingsCheckpointFrequencyEnum); _assert_(checkpoint_frequency>0);
    296301
     
    343348
    344349                /*Go through our dependent variables, and compute the response:*/
    345                 if(finaltime==time){
    346                         DataSet* dependent_objects=((DataSetParam*)femmodel->parameters->FindParamObject(AutodiffDependentObjectsEnum))->value;
    347                         for(Object* & object:dependent_objects->objects){
    348                                 DependentObject* dep=(DependentObject*)object;
    349                                 dep->Responsex(&output_value,femmodel);
    350                                 dep->AddValue(output_value);
    351                         }
     350                DataSet* dependent_objects=((DataSetParam*)femmodel->parameters->FindParamObject(AutodiffDependentObjectsEnum))->value;
     351                for(Object* & object:dependent_objects->objects){
     352                        DependentObject* dep=(DependentObject*)object;
     353                        dep->Responsex(&output_value,femmodel);
     354                        dep->AddValue(output_value);
    352355                }
    353356
     
    395398        SetControlInputsFromVectorx(femmodel,X);
    396399
    397         IssmDouble J = 0.;
     400        IssmDouble J     = 0.;
     401        int        count = 0;
    398402        DataSet* dependent_objects=((DataSetParam*)femmodel->parameters->FindParamObject(AutodiffDependentObjectsEnum))->value;
    399403        for(Object* & object:dependent_objects->objects){
    400404                DependentObject* dep=(DependentObject*)object;
    401                 J += dep->GetValue();
    402         }
    403         tape_codi.registerOutput(J);
     405                IssmDouble       output_value = dep->GetValue();
     406
     407
     408                J += output_value;
     409
     410                tape_codi.registerOutput(J);
     411                #if _CODIPACK_MAJOR_==2
     412                codi_global.output_indices.push_back(J.getIdentifier());
     413                #elif _CODIPACK_MAJOR_==1
     414                codi_global.output_indices.push_back(J.getGradientData());
     415                #else
     416                #error "_CODIPACK_MAJOR_ not supported"
     417                #endif
     418
     419                /*Keep track of output for printing*/
     420                Jlist[count] = output_value.getValue();
     421      count++;
     422        }
     423        Jlist[count] = J.getValue();
     424        _assert_(count == num_responses);
    404425
    405426        tape_codi.setPassive();
    406         if(IssmComm::GetRank()==0) J.gradient() = 1.0;
    407         tape_codi.evaluate();
     427
     428        if(VerboseAutodiff())_printf0_("   CoDiPack fos_reverse\n");
     429        for(int i=0;i<num_responses;i++){
     430                if(my_rank==0) tape_codi.setGradient(codi_global.output_indices[i],1.0);
     431                tape_codi.evaluate();
     432        }
    408433
    409434        /*Initialize Xb and Yb*/
     
    444469                        femmodel->parameters->SetParam(thisstep,StepEnum);
    445470                        femmodel->parameters->SetParam(thisdt,TimesteppingTimeStepEnum);
    446                         _printf0_("step "<<thisstep<<" ("<<ii+1<<"/"<<checkpoint_frequency<<") time [yr]: "\
    447                                                 <<std::fixed<<std::setprecision(2)<<thistime/yts<< " (time step: " << thisdt/yts << ")\n");
     471
     472                        if(VerboseSolution()){
     473                                _printf0_("step "<<thisstep<<" ("<<ii+1<<"/"<<checkpoint_frequency<<") time [yr]: "\
     474                                                        <<std::fixed<<std::setprecision(2)<<thistime/yts<< " (time step: " << thisdt/yts << ")\n");
     475                        }
     476
    448477                        transient_step(femmodel);
    449478
    450479                        /*Go through our dependent variables, and compute the response:*/
    451                         if(thistime==finaltime){
    452                                 DataSet* dependent_objects=((DataSetParam*)femmodel->parameters->FindParamObject(AutodiffDependentObjectsEnum))->value;
    453                                 for(Object* & object:dependent_objects->objects){
    454                                         DependentObject* dep=(DependentObject*)object;
    455                                         dep->Responsex(&output_value,femmodel);
    456                                         dep->AddValue(output_value);
    457                                 }
     480                        DataSet* dependent_objects=((DataSetParam*)femmodel->parameters->FindParamObject(AutodiffDependentObjectsEnum))->value;
     481                        for(Object* & object:dependent_objects->objects){
     482                                DependentObject* dep=(DependentObject*)object;
     483                                dep->Responsex(&output_value,femmodel);
     484                                dep->AddValue(output_value);
    458485                        }
    459486
     
    484511                for(int i=0; i<Xsize;   i++) Xb[i] += X[i].gradient();
    485512        }
     513
    486514        /*Clear tape*/
    487515        tape_codi.reset();
    488516
    489517        /*Broadcast gradient to other ranks (make sure to sum all gradients)*/
    490         double* gradient=xNew<double>(Xsize);
    491         ISSM_MPI_Allreduce(Xb,gradient,Xsize,ISSM_MPI_PDOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
    492 
    493         /*Now set final gradient*/
    494         IssmDouble* aG=xNew<IssmDouble>(Xsize);
    495         for(int i=0;i<Xsize;i++) aG[i] = reCast<IssmDouble>(gradient[i]);
    496         xDelete<double>(gradient);
    497         ControlInputSetGradientx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,aG);
    498         xDelete<IssmDouble>(aG);
    499 
     518        ISSM_MPI_Allreduce(Xb,G,Xsize,ISSM_MPI_PDOUBLE,ISSM_MPI_SUM,IssmComm::GetComm());
     519
     520        /*Cleanup and return misfit*/
    500521        xDelete<IssmDouble>(X);
    501522        xDelete<double>(Xb);
    502523        xDelete<double>(Yb);
    503524        xDelete<int>(Yin);
     525   return J.getValue();
    504526}/*}}}*/
    505527#endif
  • issm/trunk/src/c/datastructures/DataSet.cpp

    r26744 r27035  
    261261                                this->AddObject(cfsurf);
    262262                        }
     263                        else if(obj_enum==CfsurfacelogvelEnum){
     264                                Cfsurfacelogvel* cfsurf=new Cfsurfacelogvel();
     265                                cfsurf->Marshall(marshallhandle);
     266                                this->AddObject(cfsurf);
     267                        }
    263268                        else if(obj_enum==MassfluxatgateEnum){
    264269                                Massfluxatgate<IssmDouble>* massfluxgate=new Massfluxatgate<IssmDouble>();
  • issm/trunk/src/c/modules/Calvingx/Calvingx.cpp

    r26744 r27035  
    1515        /*Calculate calving rate*/
    1616        switch(calvinglaw){
    17                 case DefaultCalvingEnum:
    1817                case CalvingMinthicknessEnum:
    1918                case CalvingHabEnum:
     19                        femmodel->ElementOperationx(&Element::CalvingSetZeroRate);
     20                        break;
     21                case DefaultCalvingEnum:
     22                        femmodel->ElementOperationx(&Element::CalvingFromRate);
    2023                        break;
    2124                case CalvingCrevasseDepthEnum:
     25                        femmodel->ElementOperationx(&Element::CalvingSetZeroRate);
     26                        /*rate is 0 but we need to calculate a few things to determine where it will calve*/
    2227                        femmodel->StrainRateparallelx();
    2328                        femmodel->StrainRateeffectivex();
     
    3540                        femmodel->ElementOperationx(&Element::CalvingRateVonmises);
    3641                        break;
     42                case CalvingTestEnum:
     43                        femmodel->ElementOperationx(&Element::CalvingRateTest);
     44                        break;
     45                case CalvingParameterizationEnum:
     46                        femmodel->ElementOperationx(&Element::CalvingRateParameterization);
     47                        break;
    3748                default:
    3849                        _error_("Caving law "<<EnumToStringx(calvinglaw)<<" not supported yet");
  • issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.cpp

    r26744 r27035  
    4545                        if(VerboseSolution())_printf0_("        call BeckmannGoosse Floating melting rate module\n");
    4646                        BeckmannGoosseFloatingiceMeltingRatex(femmodel);
     47                        break;
     48                case AutoregressionLinearFloatingMeltRateEnum:
     49                        if(VerboseSolution())_printf0_("        call Autoregression Linear Floating melting rate module\n");
     50                        AutoregressionLinearFloatingiceMeltingRatex(femmodel);
    4751                        break;
    4852                default:
     
    206210}
    207211/*}}}*/
     212void AutoregressionLinearFloatingiceMeltingRateInitx(FemModel* femmodel){/*{{{*/
     213
     214        /*Initialization step of AutoregressionLinearFloatingiceMeltingRatex*/
     215   int M,N,Nphi,arorder,numbasins,my_rank;
     216   IssmDouble starttime,tstep_ar,tinit_ar;
     217   femmodel->parameters->FindParam(&numbasins,BasalforcingsLinearNumBasinsEnum);
     218   femmodel->parameters->FindParam(&arorder,BasalforcingsAutoregressiveOrderEnum);
     219   IssmDouble* beta0    = NULL;
     220   IssmDouble* beta1    = NULL;
     221   IssmDouble* phi      = NULL;
     222   femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
     223   femmodel->parameters->FindParam(&tstep_ar,BasalforcingsAutoregressionTimestepEnum);
     224   femmodel->parameters->FindParam(&tinit_ar,BasalforcingsAutoregressionInitialTimeEnum);
     225   femmodel->parameters->FindParam(&beta0,&M,BasalforcingsBeta0Enum);    _assert_(M==numbasins);
     226   femmodel->parameters->FindParam(&beta1,&M,BasalforcingsBeta1Enum);    _assert_(M==numbasins);
     227   femmodel->parameters->FindParam(&phi,&M,&Nphi,BasalforcingsPhiEnum);  _assert_(M==numbasins); _assert_(Nphi==arorder);
     228       
     229        /*AR model spin-up with 0 noise to initialize BasalforcingsDeepwaterMeltingRateValuesAutoregressionEnum (688 = log(0.001)/log(0.99): decaying time of inluence of phi[0]=0.99 to 0.001 of beta_0*/
     230   int nspin = 688;
     231   for(Object* &object:femmodel->elements->objects){
     232      Element* element = xDynamicCast<Element*>(object); //generate element object
     233      element->AutoregressionInit(numbasins,arorder,nspin,starttime,tstep_ar,tinit_ar,beta0,beta1,phi,BasalforcingsDeepwaterMeltingRateAutoregressionEnum);
     234        }
     235        /*Cleanup*/
     236   xDelete<IssmDouble>(beta0);
     237   xDelete<IssmDouble>(beta1);
     238   xDelete<IssmDouble>(phi);
     239}/*}}}*/
     240void AutoregressionLinearFloatingiceMeltingRatex(FemModel* femmodel){/*{{{*/
     241
     242        /*Get time parameters*/
     243   IssmDouble time,dt,starttime,tstep_ar;
     244   femmodel->parameters->FindParam(&time,TimeEnum);
     245   femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
     246   femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
     247   femmodel->parameters->FindParam(&tstep_ar,BasalforcingsAutoregressionTimestepEnum);
     248
     249   /*Initialize module at first time step*/
     250   if(time<=starttime+dt){AutoregressionLinearFloatingiceMeltingRateInitx(femmodel);}
     251   /*Determine if this is a time step for the AR model*/
     252   bool isstepforar = false;
     253
     254   #ifndef _HAVE_AD_
     255   if((fmod(time,tstep_ar)<fmod((time-dt),tstep_ar)) || (time<=starttime+dt) || tstep_ar==dt) isstepforar = true;
     256   #else
     257   _error_("not implemented yet");
     258   #endif
     259
     260   /*Load parameters*/
     261   bool isstochastic;
     262   bool isdeepmeltingstochastic = false;
     263   int M,N,Nphi,arorder,numbasins,my_rank;
     264   femmodel->parameters->FindParam(&numbasins,BasalforcingsLinearNumBasinsEnum);
     265        femmodel->parameters->FindParam(&arorder,BasalforcingsAutoregressiveOrderEnum);
     266   IssmDouble tinit_ar;
     267   IssmDouble* beta0          = NULL;
     268   IssmDouble* beta1          = NULL;
     269   IssmDouble* phi            = NULL;
     270   IssmDouble* deepwaterel    = NULL;
     271   IssmDouble* upperwaterel   = NULL;
     272   IssmDouble* upperwatermelt = NULL;
     273   IssmDouble* perturbation   = NULL;
     274
     275        /*Get autoregressive parameters*/
     276   femmodel->parameters->FindParam(&tinit_ar,BasalforcingsAutoregressionInitialTimeEnum);
     277   femmodel->parameters->FindParam(&beta0,&M,BasalforcingsBeta0Enum);               _assert_(M==numbasins);
     278   femmodel->parameters->FindParam(&beta1,&M,BasalforcingsBeta1Enum);               _assert_(M==numbasins);
     279   femmodel->parameters->FindParam(&phi,&M,&Nphi,BasalforcingsPhiEnum);             _assert_(M==numbasins); _assert_(Nphi==arorder);
     280
     281        /*Get basin-specific parameters*/
     282   femmodel->parameters->FindParam(&deepwaterel,&M,BasalforcingsDeepwaterElevationEnum);            _assert_(M==numbasins);
     283   femmodel->parameters->FindParam(&upperwaterel,&M,BasalforcingsUpperwaterElevationEnum);          _assert_(M==numbasins);
     284   femmodel->parameters->FindParam(&upperwatermelt,&M,BasalforcingsUpperwaterMeltingRateEnum);      _assert_(M==numbasins);
     285
     286        /*Evaluate whether stochasticity on DeepwaterMeltingRate is requested*/
     287        femmodel->parameters->FindParam(&isstochastic,StochasticForcingIsStochasticForcingEnum);
     288   if(isstochastic){
     289      int  numstochasticfields;
     290      int* stochasticfields;
     291      femmodel->parameters->FindParam(&numstochasticfields,StochasticForcingNumFieldsEnum);
     292      femmodel->parameters->FindParam(&stochasticfields,&N,StochasticForcingFieldsEnum); _assert_(N==numstochasticfields);
     293      for(int i=0;i<numstochasticfields;i++){
     294         if(stochasticfields[i]==BasalforcingsDeepwaterMeltingRateAutoregressionEnum) isdeepmeltingstochastic = true;
     295      }
     296      xDelete<int>(stochasticfields);
     297   }
     298   /*Time elapsed with respect to AR model initial time*/
     299   IssmDouble telapsed_ar = time-tinit_ar;
     300
     301        /*Loop over each element to compute FloatingiceMeltingRate at vertices*/
     302   for(Object* &object:femmodel->elements->objects){
     303      Element* element = xDynamicCast<Element*>(object);
     304      /*Compute autoregression*/
     305      element->Autoregression(isstepforar,arorder,telapsed_ar,beta0,beta1,phi,isdeepmeltingstochastic,BasalforcingsDeepwaterMeltingRateAutoregressionEnum);
     306                element->BasinLinearFloatingiceMeltingRate(deepwaterel,upperwatermelt,upperwaterel,perturbation);
     307        }
     308
     309        /*Cleanup*/
     310        xDelete<IssmDouble>(beta0);
     311        xDelete<IssmDouble>(beta1);
     312        xDelete<IssmDouble>(phi);
     313        xDelete<IssmDouble>(deepwaterel);
     314        xDelete<IssmDouble>(upperwaterel);
     315        xDelete<IssmDouble>(upperwatermelt);
     316        xDelete<IssmDouble>(perturbation);
     317}/*}}}*/
  • issm/trunk/src/c/modules/FloatingiceMeltingRatex/FloatingiceMeltingRatex.h

    r24313 r27035  
    1616void FloatingiceMeltingRateIsmip6x(FemModel* femmodel);
    1717void BeckmannGoosseFloatingiceMeltingRatex(FemModel* femmodel);
     18void AutoregressionLinearFloatingiceMeltingRateInitx(FemModel* femmodel);
     19void AutoregressionLinearFloatingiceMeltingRatex(FemModel* femmodel);
    1820
    1921#endif  /* _FloatingiceMeltingRatex_H*/
  • issm/trunk/src/c/modules/FrontalForcingsx/FrontalForcingsx.cpp

    r26744 r27035  
    4646   femmodel->parameters->FindParam(&phi,&M,&Nphi,FrontalForcingsPhiEnum);  _assert_(M==numbasins); _assert_(Nphi==arorder);
    4747
    48    /*AR model spin-up with 0 noise to initialize ThermalforcingValuesAutoregressionEnum*/
    49         int nspin{2*arorder+5};
     48   /*AR model spin-up with 0 noise to initialize ThermalforcingValuesAutoregressionEnum (688 = log(0.001)/log(0.99): decaying time of inluence of phi[0]=0.99 to 0.001 of beta_0*/
     49        int nspin = 688;
    5050   for(Object* &object:femmodel->elements->objects){
    5151      Element* element      = xDynamicCast<Element*>(object); //generate element object
  • issm/trunk/src/c/modules/GetVectorFromInputsx/GetVectorFromInputsx.h

    r26744 r27035  
    99/* local prototypes: */
    1010void    GetVectorFromInputsx(Vector<IssmDouble>** pvector,FemModel* femmodel,int name,int type);
    11 void    GetVectoronBaseFromInputsx(Vector<IssmDouble>** pvector,FemModel* femmodel,int name,int type);
    1211void  GetVectorFromInputsx(Vector<IssmDouble>** pvector,FemModel* femmodel,int name,int type,IssmDouble time);
    1312void    GetVectorFromInputsx(IssmDouble** pvector,FemModel* femmodel,int name,int type);
    14 void    GetVectoronBaseFromInputsx(IssmDouble** pvector,FemModel* femmodel,int name,int type);
    1513void  GetVectorFromInputsx(IssmDouble** pvector,int* pvector_size, FemModel* femmodel,int name);
    1614
     15void    GetVectoronBaseFromInputsx(IssmDouble** pvector,FemModel* femmodel,int name,int type);
     16void    GetVectoronBaseFromInputsx(Vector<IssmDouble>** pvector,FemModel* femmodel,int name,int type);
     17
    1718#endif  /* _GETVECTORFROMINPUTSXX_H */
  • issm/trunk/src/c/modules/KillIcebergsx/KillIcebergsx.cpp

    r25836 r27035  
    99#include "../InputUpdateFromVectorx/InputUpdateFromVectorx.h"
    1010
    11 void KillIcebergsx(FemModel* femmodel){
     11int KillIcebergsx(FemModel* femmodel){
    1212
    1313        /*Intermediaries*/
     
    1818        IssmDouble *local_mask   = xNewZeroInit<IssmDouble>(nbv_local);
    1919        bool       *element_flag = xNewZeroInit<bool>(femmodel->elements->Size());
     20        IssmDouble ice;
    2021
    2122        /*Step 1, go through all elements and put 1 in local_mask if the element is grounded*/
     
    2728                        element_flag[i] = true;
    2829                }
    29                 else{
    30                         if(element->IsGrounded()){
     30                else {
     31                        if(element->IsAllGrounded()){
     32                                /* only look at element with ice but not fully grounded */
    3133                                int numvertices = element->GetNumberOfVertices();
    32                                 for(int v=0;v<numvertices;v++) local_mask[element->vertices[v]->Lid()] = 1.;
     34                                Gauss* gauss=element->NewGauss();
     35                                Input* icelevel_input = element->GetInput(MaskIceLevelsetEnum);                         _assert_(icelevel_input);
     36
     37                                for(int v=0;v<numvertices;v++) {
     38                                        gauss->GaussVertex(v);
     39                                        icelevel_input->GetInputValue(&ice,gauss);
     40                                        /* The initial mask is very strict, we look at all grounded elements and set the mask for ice nodes only. */
     41                                        if (ice < 0) local_mask[element->vertices[v]->Lid()] = 1.;
     42                                }
     43                                delete gauss;
    3344                        }
    3445                }
     
    4859                /*Local iterations on partition*/
    4960                bool keepgoing    = true;
    50                 int  didsomething = 0;
    5161                int  iter         = 1;
    5262                while(keepgoing){
     
    5464
    5565                        keepgoing    = false;
    56                         didsomething = 0;
    5766                        int i=0;
    5867                        for(Object* & object : femmodel->elements->objects){
     
    6271                                        int numvertices = element->GetNumberOfVertices();
    6372                                        bool found1 = false;
     73                                        IssmDouble sumlocalmask = 0.;
     74
    6475                                        for(int j=0;j<numvertices;j++){
    6576                                                lid = element->vertices[j]->Lid();
    66                                                 if(local_mask[lid]>0.){
     77                                                /*we need to have at least a sharing edge, to extend the mask*/
     78                                                sumlocalmask += local_mask[lid];
     79                                                if(sumlocalmask > 1.5){
    6780                                                        found1 = true;
    6881                                                        break;
     
    7386                                                for(int j=0;j<numvertices;j++){
    7487                                                        lid = element->vertices[j]->Lid();
    75                                                         if(local_mask[lid]==0.){
    76                                                                 local_mask[lid]=1.;
    77                                                                 keepgoing = true;
    78                                                                 didsomething = 1;
    79                                                         }
     88                                                        local_mask[lid]=1.;
    8089                                                }
     90                                                keepgoing = true;
    8191                                        }
    8292                                }
     
    99109        xDelete<bool>(element_flag);
    100110
     111        int killbergReinit = 0;
    101112        /*OK, now deactivate iceberg and count the number of deactivated vertices*/
    102113        for(Object* & object : femmodel->elements->objects){
     
    120131                                element->AddInput(MaskIceLevelsetEnum,values,P1Enum);
    121132                                xDelete<IssmDouble>(values);
     133                                killbergReinit += 1;
    122134                        }
    123135                }
    124136        }
    125 
    126137        /*cleanup*/
    127138        xDelete<IssmDouble>(local_mask);
     139
     140        /*Recompute the sign distance for the levelset function*/
     141        return killbergReinit;
    128142}
  • issm/trunk/src/c/modules/KillIcebergsx/KillIcebergsx.h

    r23992 r27035  
    66
    77/* local prototypes: */
    8 void KillIcebergsx(FemModel* femmodel);
     8int KillIcebergsx(FemModel* femmodel);
    99
    1010#endif
  • issm/trunk/src/c/modules/ModelProcessorx/CreateOutputDefinitions.cpp

    r26744 r27035  
    311311                                /*cfsurfacelogvel variables: */
    312312                                int          num_cfsurfacelogvels;
    313                                 char**       cfsurfacelogvel_name                                               = NULL;   
    314                                 char**           cfsurfacelogvel_definitionstring               = NULL;   
    315                                 IssmDouble** cfsurfacelogvel_vxobs                      = NULL;
    316                                 IssmDouble** cfsurfacelogvel_vyobs                      = NULL;
    317                                 char**           cfsurfacelogvel_vxobs_string   = NULL;
    318                                 char**           cfsurfacelogvel_vyobs_string   = NULL;
    319                                 int*         cfsurfacelogvel_observation_M                      = NULL;
    320                                 int*         cfsurfacelogvel_observation_N                      = NULL;
    321                                 IssmDouble** cfsurfacelogvel_weights                                    = NULL;
    322                                 int*         cfsurfacelogvel_weights_M                          = NULL;
    323                                 int*         cfsurfacelogvel_weights_N                          = NULL;
    324                                 char**       cfsurfacelogvel_weightstring               = NULL;
    325                                 IssmDouble*  cfsurfacelogvel_datatime                           = NULL;
    326 
    327                                 /*Fetch name, modeltring, observation, observationtring, etc ... (see src/m/classes/cfsurfacelogvel.m): */
    328                                 iomodel->FetchMultipleData(&cfsurfacelogvel_name,&num_cfsurfacelogvels,                                                        "md.cfsurfacelogvel.name");
    329                                 iomodel->FetchMultipleData(&cfsurfacelogvel_definitionstring,&num_cfsurfacelogvels,                                            "md.cfsurfacelogvel.definitionstring");
    330                                 iomodel->FetchMultipleData(&cfsurfacelogvel_vxobs,&cfsurfacelogvel_observation_M,&cfsurfacelogvel_observation_N,&num_cfsurfacelogvels, "md.cfsurfacelogvel.vxobs");
    331                                 iomodel->FetchMultipleData(&cfsurfacelogvel_vxobs_string,&num_cfsurfacelogvels,                                          "md.cfsurfacelogvel.vxobs_string");
    332                                 iomodel->FetchMultipleData(&cfsurfacelogvel_vyobs,&cfsurfacelogvel_observation_M,&cfsurfacelogvel_observation_N,&num_cfsurfacelogvels, "md.cfsurfacelogvel.vyobs");
    333                                 iomodel->FetchMultipleData(&cfsurfacelogvel_vyobs_string,&num_cfsurfacelogvels,                                          "md.cfsurfacelogvel.vyobs_string");                    iomodel->FetchMultipleData(&cfsurfacelogvel_weights,&cfsurfacelogvel_weights_M,&cfsurfacelogvel_weights_N,&num_cfsurfacelogvels,             "md.cfsurfacelogvel.weights");
    334                                 iomodel->FetchMultipleData(&cfsurfacelogvel_weightstring,&num_cfsurfacelogvels,                                              "md.cfsurfacelogvel.weights_string");
    335                                 iomodel->FetchMultipleData(&cfsurfacelogvel_datatime,&num_cfsurfacelogvels,                                                                                                                                      "md.cfsurfacelogvel.datatime");
     313                                char       **cfsurfacelogvel_name             = NULL;
     314                                char       **cfsurfacelogvel_definitionstring = NULL;
     315                                IssmDouble **cfsurfacelogvel_vxobs            = NULL;
     316                                IssmDouble **cfsurfacelogvel_vyobs            = NULL;
     317                                char       **cfsurfacelogvel_vxobs_string     = NULL;
     318                                char       **cfsurfacelogvel_vyobs_string     = NULL;
     319                                int         *cfsurfacelogvel_observation_M    = NULL;
     320                                int         *cfsurfacelogvel_observation_N    = NULL;
     321                                IssmDouble **cfsurfacelogvel_weights          = NULL;
     322                                int         *cfsurfacelogvel_weights_M        = NULL;
     323                                int         *cfsurfacelogvel_weights_N        = NULL;
     324                                char       **cfsurfacelogvel_weightstring     = NULL;
     325                                IssmDouble  *cfsurfacelogvel_datatime         = NULL;
     326
     327            /*Fetch name, modeltring, observation, observationtring, etc ... (see src/m/classes/cfsurfacelogvel.m): */
     328            iomodel->FetchMultipleData(&cfsurfacelogvel_name,&num_cfsurfacelogvels,"md.cfsurfacelogvel.name");
     329            iomodel->FetchMultipleData(&cfsurfacelogvel_definitionstring,&num_cfsurfacelogvels,"md.cfsurfacelogvel.definitionstring");
     330            iomodel->FetchMultipleData(&cfsurfacelogvel_vxobs,&cfsurfacelogvel_observation_M,&cfsurfacelogvel_observation_N,&num_cfsurfacelogvels,"md.cfsurfacelogvel.vxobs");
     331            iomodel->FetchMultipleData(&cfsurfacelogvel_vxobs_string,&num_cfsurfacelogvels,"md.cfsurfacelogvel.vxobs_string");
     332            iomodel->FetchMultipleData(&cfsurfacelogvel_vyobs,NULL,NULL,&num_cfsurfacelogvels,"md.cfsurfacelogvel.vyobs");
     333            iomodel->FetchMultipleData(&cfsurfacelogvel_vyobs_string,&num_cfsurfacelogvels,"md.cfsurfacelogvel.vyobs_string");
     334            iomodel->FetchMultipleData(&cfsurfacelogvel_weights,&cfsurfacelogvel_weights_M,&cfsurfacelogvel_weights_N,&num_cfsurfacelogvels,"md.cfsurfacelogvel.weights");
     335            iomodel->FetchMultipleData(&cfsurfacelogvel_weightstring,&num_cfsurfacelogvels,"md.cfsurfacelogvel.weights_string");
     336            iomodel->FetchMultipleData(&cfsurfacelogvel_datatime,&num_cfsurfacelogvels,"md.cfsurfacelogvel.datatime");
    336337
    337338                                for(j=0;j<num_cfsurfacelogvels;j++){
  • issm/trunk/src/c/modules/ModelProcessorx/CreateParameters.cpp

    r26744 r27035  
    252252                        break;
    253253                case BeckmannGoosseFloatingMeltRateEnum:
     254                        break;
     255                case AutoregressionLinearFloatingMeltRateEnum:
     256                        /*Add parameters that are not in standard nbvertices format*/
     257         parameters->AddObject(iomodel->CopyConstantObject("md.basalforcings.num_basins",BasalforcingsLinearNumBasinsEnum));
     258         parameters->AddObject(iomodel->CopyConstantObject("md.basalforcings.ar_order",BasalforcingsAutoregressiveOrderEnum));
     259         parameters->AddObject(iomodel->CopyConstantObject("md.basalforcings.ar_initialtime",BasalforcingsAutoregressionInitialTimeEnum));
     260         parameters->AddObject(iomodel->CopyConstantObject("md.basalforcings.ar_timestep",BasalforcingsAutoregressionTimestepEnum));
     261                        iomodel->FetchData(&transparam,&M,&N,"md.basalforcings.beta0");
     262         parameters->AddObject(new DoubleVecParam(BasalforcingsBeta0Enum,transparam,N));
     263         xDelete<IssmDouble>(transparam);
     264         iomodel->FetchData(&transparam,&M,&N,"md.basalforcings.beta1");
     265         parameters->AddObject(new DoubleVecParam(BasalforcingsBeta1Enum,transparam,N));
     266         xDelete<IssmDouble>(transparam);
     267         iomodel->FetchData(&transparam,&M,&N,"md.basalforcings.phi");
     268         parameters->AddObject(new DoubleMatParam(BasalforcingsPhiEnum,transparam,M,N));
     269         xDelete<IssmDouble>(transparam);
     270                        iomodel->FetchData(&transparam,&M,&N,"md.basalforcings.upperwater_melting_rate");
     271         parameters->AddObject(new DoubleVecParam(BasalforcingsUpperwaterMeltingRateEnum,transparam,N));
     272         xDelete<IssmDouble>(transparam);   
     273         iomodel->FetchData(&transparam,&M,&N,"md.basalforcings.upperwater_elevation");
     274         parameters->AddObject(new DoubleVecParam(BasalforcingsUpperwaterElevationEnum,transparam,N));
     275         xDelete<IssmDouble>(transparam);
     276                        iomodel->FetchData(&transparam,&M,&N,"md.basalforcings.deepwater_elevation");
     277         parameters->AddObject(new DoubleVecParam(BasalforcingsDeepwaterElevationEnum,transparam,N));
     278         xDelete<IssmDouble>(transparam);   
    254279                        break;
    255280                default:
     
    403428         parameters->AddObject(iomodel->CopyConstantObject("md.smb.ar_initialtime",SmbAutoregressionInitialTimeEnum));
    404429         parameters->AddObject(iomodel->CopyConstantObject("md.smb.ar_timestep",SmbAutoregressionTimestepEnum));
     430         parameters->AddObject(iomodel->CopyConstantObject("md.smb.num_bins",SmbNumElevationBinsEnum));
    405431         iomodel->FetchData(&transparam,&M,&N,"md.smb.beta0");
    406432         parameters->AddObject(new DoubleVecParam(SmbBeta0Enum,transparam,N));
     
    412438         parameters->AddObject(new DoubleMatParam(SmbPhiEnum,transparam,M,N));
    413439         xDelete<IssmDouble>(transparam);
    414          break;
     440         iomodel->FetchData(&transparam,&M,&N,"md.smb.lapserates");
     441         parameters->AddObject(new DoubleMatParam(SmbLapseRatesEnum,transparam,M,N));
     442         xDelete<IssmDouble>(transparam);
     443         iomodel->FetchData(&transparam,&M,&N,"md.smb.elevationbins");
     444         parameters->AddObject(new DoubleMatParam(SmbElevationBinsEnum,transparam,M,N));
     445         xDelete<IssmDouble>(transparam);
     446                        iomodel->FetchData(&transparam,&M,&N,"md.smb.refelevation");
     447         parameters->AddObject(new DoubleVecParam(SmbRefElevationEnum,transparam,N));
     448         xDelete<IssmDouble>(transparam);
     449                        break;
    415450                case SMBgembEnum:
    416451                        parameters->AddObject(iomodel->CopyConstantObject("md.smb.aIce",SmbAIceEnum));
     
    486521        }
    487522        else if(hydrology_model==HydrologyGlaDSEnum){
     523                /*Nothing to add*/
     524        }
     525        else if(hydrology_model==HydrologyTwsEnum){
    488526                /*Nothing to add*/
    489527        }
     
    508546      parameters->AddObject(iomodel->CopyConstantObject("md.stochasticforcing.num_fields",StochasticForcingNumFieldsEnum));
    509547      parameters->AddObject(iomodel->CopyConstantObject("md.stochasticforcing.defaultdimension",StochasticForcingDefaultDimensionEnum));
     548      parameters->AddObject(iomodel->CopyConstantObject("md.stochasticforcing.stochastictimestep",StochasticForcingTimestepEnum));
    510549      iomodel->FindConstant(&fields,&num_fields,"md.stochasticforcing.fields");
    511550      if(num_fields<1) _error_("no stochasticforcing fields found");
  • issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.cpp

    r26744 r27035  
    8181        UpdateElementsAndMaterialsDakota(elements,inputs,materials,iomodel);
    8282        #endif
    83         if(solution_enum==TransientSolutionEnum) UpdateElementsTransient(elements,parameters,inputs,iomodel);
    84 
     83        if(solution_enum==TransientSolutionEnum){
     84                UpdateParametersTransient(parameters,iomodel);
     85                UpdateElementsTransient(elements,parameters,inputs,iomodel);
     86        }
    8587        /*Output definitions dataset: */
    8688        if(VerboseMProcessor()) _printf0_("   creating output definitions" << "\n");
  • issm/trunk/src/c/modules/ModelProcessorx/ModelProcessorx.h

    r25836 r27035  
    2424void UpdateElementsAndMaterialsDakota(Elements* elements,Inputs* inputs,Materials* materials, IoModel* iomodel);
    2525void UpdateElementsTransient(Elements* elements,Parameters* parameters,Inputs* inputs,IoModel* iomodel);
     26void UpdateParametersTransient(Parameters* parameters,IoModel* iomodel);
    2627void CreateNodes(Nodes*nodes, IoModel* iomodel,int analysis,int finite_element,bool isamr=false,int approximation=NoneApproximationEnum,int* approximations=NULL);
    2728
  • issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.cpp

    r25836 r27035  
    4040        xDelete<IssmDouble>(serial_vector);
    4141}
     42#ifdef _HAVE_AD_
     43void SetControlInputsFromVectorx(FemModel* femmodel,IssmPDouble* vector){
     44
     45        /*Get total size and recast*/
     46        int  num_controls;
     47        int* M = NULL;
     48        int* N = NULL;
     49        femmodel->parameters->FindParam(&num_controls,InversionNumControlParametersEnum);
     50        femmodel->parameters->FindParam(&M,NULL,ControlInputSizeMEnum);
     51        femmodel->parameters->FindParam(&N,NULL,ControlInputSizeNEnum);
     52
     53        int size = 0;
     54        for(int i=0;i<num_controls;i++) size += M[i]*N[i];
     55
     56        IssmDouble* serial_vector=xNew<IssmDouble>(size);
     57        for(int i=0;i<size;i++) serial_vector[i] = reCast<IssmDouble>(vector[i]);
     58
     59        SetControlInputsFromVectorx(femmodel,serial_vector);
     60
     61        xDelete<IssmDouble>(serial_vector);
     62        xDelete<int>(M);
     63        xDelete<int>(N);
     64}
     65#endif
  • issm/trunk/src/c/modules/SetControlInputsFromVectorx/SetControlInputsFromVectorx.h

    r18301 r27035  
    1111void SetControlInputsFromVectorx(FemModel* femmodel,IssmDouble* vector);
    1212
     13#ifdef _HAVE_AD_
     14void SetControlInputsFromVectorx(FemModel* femmodel,IssmPDouble* vector);
     15#endif
     16
    1317#endif
  • issm/trunk/src/c/modules/Solverx/Solverx.cpp

    r24686 r27035  
    6565        /*Check convergence*/
    6666        if(solver_residue>solver_residue_threshold){
    67                 _printf0_("solver residue too high!: norm(KU-F)/norm(F)=" << solver_residue << " > "<<solver_residue_threshold<<" (md.settings.solver_residue_threshold)");
     67                _printf0_("solver residue too high!: norm(KU-F)/norm(F)=" << solver_residue << " > "<<solver_residue_threshold<<" (md.settings.solver_residue_threshold)\n");
    6868                return false;
    6969        }
  • issm/trunk/src/c/modules/StochasticForcingx/StochasticForcingx.cpp

    r26676 r27035  
    1111void StochasticForcingx(FemModel* femmodel){/*{{{*/
    1212
    13 
    14         //VV testing (12Nov)
    15         /*
    16         IssmDouble timeVV,dtVV,starttimeVV;
    17         femmodel->parameters->FindParam(&timeVV,TimeEnum);
    18    femmodel->parameters->FindParam(&dtVV,TimesteppingTimeStepEnum);
    19    femmodel->parameters->FindParam(&starttimeVV,TimesteppingStartTimeEnum);
    20         IssmDouble valMean = 0;
    21         IssmDouble valSdev = 0.5;
    22         int seed;
    23         //seed = reCast<int,IssmDouble>((timeVV-starttimeVV)/dtVV);
    24         seed = -1;
    25         IssmDouble rdmVV;
    26         univariateNormal_test0(&rdmVV,valMean,valSdev,seed);
    27         _printf_("VV rdmVV: "<<rdmVV<<'\n');
    28         */
    2913
    3014   /*Retrieve parameters*/
     
    4226   femmodel->parameters->FindParam(&covariance,&M,&N,StochasticForcingCovarianceEnum); _assert_(M==dimtot); _assert_(N==dimtot);
    4327
     28        /*Check if this is a timestep for new noiseterms computation*/
     29        bool isstepforstoch = false;
     30        IssmDouble time,dt,starttime,tstep_stoch;
     31   femmodel->parameters->FindParam(&time,TimeEnum);
     32   femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
     33   femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
     34   femmodel->parameters->FindParam(&tstep_stoch,StochasticForcingTimestepEnum);
     35               
     36        #ifndef _HAVE_AD_
     37   if((fmod(time,tstep_stoch)<fmod((time-dt),tstep_stoch)) || (time<=starttime+dt) || tstep_stoch==dt) isstepforstoch = true;
     38   #else
     39   _error_("not implemented yet");
     40   #endif
     41
    4442   /*Compute noise terms*/
    45    IssmDouble* noiseterms = xNew<IssmDouble>(dimtot);
    46    my_rank=IssmComm::GetRank();
    47    if(my_rank==0){
    48       int fixedseed;
    49       IssmDouble time,dt,starttime;
    50       femmodel->parameters->FindParam(&time,TimeEnum);
    51       femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
    52       femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
    53                 /*Determine whether random seed is fixed to time step (randomflag==false) or random seed truly random (randomflag==true)*/
    54       if(randomflag) fixedseed=-1;
    55       else fixedseed = reCast<int,IssmDouble>((time-starttime)/dt);
    56                 /*multivariateNormal needs to be passed a NULL pointer to avoid memory leak issues*/
    57       IssmDouble* temparray = NULL;
    58       multivariateNormal(&temparray,dimtot,0.0,covariance,fixedseed);
    59       for(int i=0;i<dimtot;i++) noiseterms[i]=temparray[i];
    60       xDelete<IssmDouble>(temparray);
    61    }
    62    ISSM_MPI_Bcast(noiseterms,dimtot,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
    63    
     43        IssmDouble* noiseterms = xNew<IssmDouble>(dimtot);
     44   if(isstepforstoch){
     45                my_rank=IssmComm::GetRank();
     46        if(my_rank==0){
     47           int fixedseed;
     48                        /*Determine whether random seed is fixed to time step (randomflag==false) or random seed truly random (randomflag==true)*/
     49           if(randomflag) fixedseed=-1;
     50           else fixedseed = reCast<int,IssmDouble>((time-starttime)/dt);
     51                        /*multivariateNormal needs to be passed a NULL pointer to avoid memory leak issues*/
     52           IssmDouble* temparray = NULL;
     53           multivariateNormal(&temparray,dimtot,0.0,covariance,fixedseed);
     54           for(int i=0;i<dimtot;i++) noiseterms[i]=temparray[i];
     55                        xDelete<IssmDouble>(temparray);
     56        }
     57        ISSM_MPI_Bcast(noiseterms,dimtot,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
     58                femmodel->parameters->SetParam(noiseterms,dimtot,StochasticForcingNoisetermsEnum);
     59        }
     60        else{
     61                IssmDouble* temparray = NULL;
     62                femmodel->parameters->FindParam(&temparray,&N,StochasticForcingNoisetermsEnum); _assert_(N==dimtot);
     63                for(int i=0;i<dimtot;i++) noiseterms[i] = temparray[i];
     64                xDelete<IssmDouble>(temparray);
     65        }
     66
    6467        int i=0;
    6568   for(int j=0;j<numfields;j++){
     
    7376
    7477                /*Deal with the autoregressive models*/
    75                 if(fields[j]==SMBautoregressionEnum || fields[j]==FrontalForcingsRignotAutoregressionEnum){
     78                if(fields[j]==SMBautoregressionEnum || fields[j]==FrontalForcingsRignotAutoregressionEnum || fields[j]==BasalforcingsDeepwaterMeltingRateAutoregressionEnum){
    7679                        switch(fields[j]){
    7780                                case SMBautoregressionEnum:
     
    8285                                        dimenum_type   = FrontalForcingsBasinIdEnum;
    8386                                        noiseenum_type = ThermalforcingAutoregressionNoiseEnum;
     87                                        break;
     88                                case BasalforcingsDeepwaterMeltingRateAutoregressionEnum:
     89                                        dimenum_type   = BasalforcingsLinearBasinIdEnum;
     90                                        noiseenum_type = BasalforcingsDeepwaterMeltingRateNoiseEnum;
    8491                                        break;
    8592                        }
     
    98105                                case SMBautoregressionEnum:
    99106                                case FrontalForcingsRignotAutoregressionEnum:
     107                                case BasalforcingsDeepwaterMeltingRateAutoregressionEnum:
    100108                                        /*Already done above*/
    101109                                        break;
     110                                case BasalforcingsSpatialDeepwaterMeltingRateEnum:
     111               /*Delete BasalforcingsSpatialDeepwaterMeltingRateEnum at previous time step (required if it is transient)*/
     112               femmodel->inputs->DeleteInput(BasalforcingsSpatialDeepwaterMeltingRateEnum);
     113               for(Object* &object:femmodel->elements->objects){
     114                  Element* element = xDynamicCast<Element*>(object);
     115                  int numvertices  = element->GetNumberOfVertices();
     116                  IssmDouble baselinedeepwatermelt;
     117                  IssmDouble deepwatermelt_tot[numvertices];
     118                  Input* baselinedeepwatermelt_input  = NULL;
     119                  baselinedeepwatermelt_input = element->GetInput(BaselineBasalforcingsSpatialDeepwaterMeltingRateEnum); _assert_(baselinedeepwatermelt_input);
     120                  element->GetInputValue(&dimensionid,StochasticForcingDefaultIdEnum);
     121                  Gauss* gauss = element->NewGauss();
     122                  for(int i=0;i<numvertices;i++){
     123                     gauss->GaussVertex(i);
     124                     baselinedeepwatermelt_input->GetInputValue(&baselinedeepwatermelt,gauss);
     125                     deepwatermelt_tot[i] = baselinedeepwatermelt+noisefield[dimensionid];
     126                  }
     127                  element->AddInput(BasalforcingsSpatialDeepwaterMeltingRateEnum,&deepwatermelt_tot[0],P1DGEnum);
     128                  delete gauss;
     129               }
     130               break;
    102131                                case DefaultCalvingEnum:
    103132                                        /*Delete CalvingCalvingrateEnum at previous time step (required if it is transient)*/
     
    136165                                                        gauss->GaussVertex(i);
    137166                                                        baselinefloatingicemeltrate_input->GetInputValue(&baselinefloatingicemeltrate,gauss);
    138                                                         floatingicemeltrate_tot[i] = max(0.0,baselinefloatingicemeltrate+noisefield[dimensionid]);
     167                                                        /*No check for positive melt rate because basal accretion is allowed*/
     168                                                        floatingicemeltrate_tot[i] = baselinefloatingicemeltrate+noisefield[dimensionid];
    139169                                                }
    140170                                                element->AddInput(BasalforcingsFloatingiceMeltingRateEnum,&floatingicemeltrate_tot[0],P1DGEnum);
     
    142172                                        }
    143173                                        break;
    144                                 //VV working(29Nov2021)
     174                                case SMBforcingEnum:
     175                                        /*Delete SmbMassBalanceEnum at previous time step (required if it is transient)*/
     176                                        femmodel->inputs->DeleteInput(SmbMassBalanceEnum);
     177                                        for(Object* &object:femmodel->elements->objects){
     178                                                Element* element = xDynamicCast<Element*>(object);
     179                                                int numvertices  = element->GetNumberOfVertices();
     180                                                IssmDouble baselinesmb;
     181                                                IssmDouble smb_tot[numvertices];
     182                                                Input* baselinesmb_input  = NULL;
     183                                                baselinesmb_input = element->GetInput(BaselineSmbMassBalanceEnum); _assert_(baselinesmb_input);
     184                                                element->GetInputValue(&dimensionid,StochasticForcingDefaultIdEnum);
     185                                                Gauss* gauss = element->NewGauss();
     186                                                for(int i=0;i<numvertices;i++){
     187                                                        gauss->GaussVertex(i);
     188                                                        baselinesmb_input->GetInputValue(&baselinesmb,gauss);
     189                                                        smb_tot[i] = baselinesmb+noisefield[dimensionid];
     190                                                }
     191                                                element->AddInput(SmbMassBalanceEnum,&smb_tot[0],P1DGEnum);
     192                                                delete gauss;
     193                                        }
     194                                        break;
    145195                                case FrictionWaterPressureEnum:
    146196                                        /*Specify that WaterPressure is stochastic*/
     
    165215                                        }
    166216                                        break;
    167 
    168                                 /*
    169                                 case FrictionEffectivePressureEnum:
    170                                         femmodel->parameters->SetParam(true,StochasticForcingIsEffectivePressureEnum);
    171                                         for(Object* &object:femmodel->elements->objects){
    172                   Element* element = xDynamicCast<Element*>(object);
    173                   int numvertices  = element->GetNumberOfVertices();
    174                   IssmDouble Neff[numvertices];
    175                                                 element->GetInputValue(&dimensionid,StochasticForcingDefaultIdEnum);
    176                                                 Gauss* gauss=element->NewGauss();
    177                                                 Friction* friction = new Friction(element);
    178                                                 for(int i=0;i<numvertices;i++){
    179                                                         gauss->GaussVertex(i);
    180                                                         Neff[i] = friction->EffectivePressure(gauss);
    181                                                         Neff[i] = Neff[i]+noisefield[dimensionid];
    182                                                 }
    183                                                 element->AddInput(FrictionEffectivePressureEnum,Neff,P1DGEnum);
    184                                                 delete gauss;
    185                                                 delete friction;
    186                                         }
    187                                         break;
    188                                 */
    189 
    190217                                default:
    191218                                        _error_("Field "<<EnumToStringx(fields[j])<<" does not support stochasticity yet.");
  • issm/trunk/src/c/modules/SurfaceAbsVelMisfitx/SurfaceAbsVelMisfitx.cpp

    r26744 r27035  
    6666        Input* vyobs_input  = NULL;
    6767
    68         /*Read SurfaceEnum from 2D models:SSA, L1L2, MLHO*/
     68        /*Read SurfaceEnum from 2D models:SSA, L1L2, MOLHO*/
    6969        if (domaintype == Domain2DhorizontalEnum) {
    7070                vx_input = topelement->GetInput(VxSurfaceEnum);                                 _assert_(vx_input);
  • issm/trunk/src/c/modules/SurfaceAverageVelMisfitx/SurfaceAverageVelMisfitx.cpp

    r26744 r27035  
    7474   Input* vyobs_input  = NULL;
    7575
    76    /*Read SurfaceEnum from 2D models:SSA, L1L2, MLHO*/
     76   /*Read SurfaceEnum from 2D models:SSA, L1L2, MOLHO*/
    7777   if (domaintype == Domain2DhorizontalEnum) {
    7878      vx_input = topelement->GetInput(VxSurfaceEnum);             _assert_(vx_input);
  • issm/trunk/src/c/modules/SurfaceLogVelMisfitx/SurfaceLogVelMisfitx.cpp

    r26744 r27035  
    6868   Input* vyobs_input  = NULL;
    6969
    70    /*Read SurfaceEnum from 2D models:SSA, L1L2, MLHO*/
     70   /*Read SurfaceEnum from 2D models:SSA, L1L2, MOLHO*/
    7171   if (domaintype == Domain2DhorizontalEnum) {
    7272      vx_input = topelement->GetInput(VxSurfaceEnum);             _assert_(vx_input);
  • issm/trunk/src/c/modules/SurfaceLogVxVyMisfitx/SurfaceLogVxVyMisfitx.cpp

    r26744 r27035  
    6868   Input* vyobs_input  = NULL;
    6969
    70    /*Read SurfaceEnum from 2D models:SSA, L1L2, MLHO*/
     70   /*Read SurfaceEnum from 2D models:SSA, L1L2, MOLHO*/
    7171   if (domaintype == Domain2DhorizontalEnum) {
    7272      vx_input = topelement->GetInput(VxSurfaceEnum);             _assert_(vx_input);
  • issm/trunk/src/c/modules/SurfaceMassBalancex/SurfaceMassBalancex.cpp

    r26744 r27035  
    164164        femmodel->parameters->FindParam(&phi,&M,&Nphi,SmbPhiEnum);  _assert_(M==numbasins); _assert_(Nphi==arorder);
    165165       
    166         /*AR model spin-up with 0 noise to initialize SmbValuesAutoregressionEnum*/
    167         int nspin{2*arorder+5};
     166        /*AR model spin-up with 0 noise to initialize SmbValuesAutoregressionEnum (688 = log(0.001)/log(0.99): decaying time of inluence of phi[0]=0.99 to 0.001 of beta_0*/
     167        int nspin = 688;
    168168        for(Object* &object:femmodel->elements->objects){
    169169      Element* element      = xDynamicCast<Element*>(object); //generate element object
     
    198198   bool isstochastic;
    199199   bool issmbstochastic = false;
    200    int M,N,Nphi,arorder,numbasins,my_rank;
     200   int M,N,Nphi,arorder,numbasins,numelevbins,my_rank;
    201201   femmodel->parameters->FindParam(&numbasins,SmbNumBasinsEnum);
    202202   femmodel->parameters->FindParam(&arorder,SmbAutoregressiveOrderEnum);
     203   femmodel->parameters->FindParam(&numelevbins,SmbNumElevationBinsEnum);
    203204   IssmDouble tinit_ar;
    204    IssmDouble* beta0      = NULL;
    205    IssmDouble* beta1      = NULL;
    206    IssmDouble* phi        = NULL;
     205   IssmDouble* beta0         = NULL;
     206   IssmDouble* beta1         = NULL;
     207   IssmDouble* phi           = NULL;
     208   IssmDouble* lapserates    = NULL;
     209   IssmDouble* elevbins      = NULL;
     210   IssmDouble* refelevation  = NULL;
    207211
    208212   femmodel->parameters->FindParam(&tinit_ar,SmbAutoregressionInitialTimeEnum);
    209    femmodel->parameters->FindParam(&beta0,&M,SmbBeta0Enum);    _assert_(M==numbasins);
    210    femmodel->parameters->FindParam(&beta1,&M,SmbBeta1Enum);    _assert_(M==numbasins);
    211    femmodel->parameters->FindParam(&phi,&M,&Nphi,SmbPhiEnum);  _assert_(M==numbasins); _assert_(Nphi==arorder);
     213   femmodel->parameters->FindParam(&beta0,&M,SmbBeta0Enum);                  _assert_(M==numbasins);
     214   femmodel->parameters->FindParam(&beta1,&M,SmbBeta1Enum);                  _assert_(M==numbasins);
     215   femmodel->parameters->FindParam(&phi,&M,&Nphi,SmbPhiEnum);                _assert_(M==numbasins); _assert_(Nphi==arorder);
     216   femmodel->parameters->FindParam(&lapserates,&M,&N,SmbLapseRatesEnum);     _assert_(M==numbasins); _assert_(N==numelevbins);
     217   femmodel->parameters->FindParam(&elevbins,&M,&N,SmbElevationBinsEnum);    _assert_(M==numbasins); _assert_(N==numelevbins-1);
     218   femmodel->parameters->FindParam(&refelevation,&M,SmbRefElevationEnum);    _assert_(M==numbasins);
    212219
    213220   femmodel->parameters->FindParam(&isstochastic,StochasticForcingIsStochasticForcingEnum);
     
    228235   for(Object* &object:femmodel->elements->objects){
    229236      Element* element = xDynamicCast<Element*>(object);
    230       element->Autoregression(isstepforar,arorder,telapsed_ar,beta0,beta1,phi,issmbstochastic,SMBautoregressionEnum);
    231    }
     237      /*Compute autoregression*/
     238                element->Autoregression(isstepforar,arorder,telapsed_ar,beta0,beta1,phi,issmbstochastic,SMBautoregressionEnum);
     239                /*Compute lapse rate adjustment*/
     240                element->LapseRateBasinSMB(numelevbins,lapserates,elevbins,refelevation);
     241        }
    232242
    233243   /*Cleanup*/
     
    235245   xDelete<IssmDouble>(beta1);
    236246   xDelete<IssmDouble>(phi);
     247   xDelete<IssmDouble>(lapserates);
     248   xDelete<IssmDouble>(elevbins);
     249   xDelete<IssmDouble>(refelevation);
    237250}/*}}}*/
    238251void Delta18oParameterizationx(FemModel* femmodel){/*{{{*/
  • issm/trunk/src/c/modules/SurfaceRelVelMisfitx/SurfaceRelVelMisfitx.cpp

    r26744 r27035  
    6868   Input* vyobs_input  = NULL;
    6969
    70    /*Read SurfaceEnum from 2D models:SSA, L1L2, MLHO*/
     70   /*Read SurfaceEnum from 2D models:SSA, L1L2, MOLHO*/
    7171   if (domaintype == Domain2DhorizontalEnum) {
    7272      vx_input = topelement->GetInput(VxSurfaceEnum);             _assert_(vx_input);
  • issm/trunk/src/c/shared/Enum/Enum.vim

    r26744 r27035  
    6464syn keyword cConstant BalancethicknessStabilizationEnum
    6565syn keyword cConstant BarystaticContributionsEnum
     66syn keyword cConstant BasalforcingsAutoregressionInitialTimeEnum
     67syn keyword cConstant BasalforcingsAutoregressionTimestepEnum
     68syn keyword cConstant BasalforcingsAutoregressiveOrderEnum
     69syn keyword cConstant BasalforcingsBeta0Enum
     70syn keyword cConstant BasalforcingsBeta1Enum
    6671syn keyword cConstant BasalforcingsBottomplumedepthEnum
    6772syn keyword cConstant BasalforcingsCrustthicknessEnum
     
    7782syn keyword cConstant BasalforcingsIsmip6NumBasinsEnum
    7883syn keyword cConstant BasalforcingsIsmip6TfDepthsEnum
     84syn keyword cConstant BasalforcingsLinearNumBasinsEnum
    7985syn keyword cConstant BasalforcingsLowercrustheatEnum
    8086syn keyword cConstant BasalforcingsMantleconductivityEnum
    8187syn keyword cConstant BasalforcingsNusseltEnum
     88syn keyword cConstant BasalforcingsPhiEnum
    8289syn keyword cConstant BasalforcingsPicoAverageOverturningEnum
    8390syn keyword cConstant BasalforcingsPicoAverageSalinityEnum
     
    105112syn keyword cConstant CalvingLawEnum
    106113syn keyword cConstant CalvingMinthicknessEnum
     114syn keyword cConstant CalvingTestSpeedfactorEnum
     115syn keyword cConstant CalvingTestIndependentRateEnum
     116syn keyword cConstant CalvingUseParamEnum
     117syn keyword cConstant CalvingScaleThetaEnum
     118syn keyword cConstant CalvingAmpAlphaEnum
     119syn keyword cConstant CalvingMidpointEnum
     120syn keyword cConstant CalvingNonlinearLawEnum
    107121syn keyword cConstant ConfigurationTypeEnum
    108122syn keyword cConstant ConstantsGEnum
     
    162176syn keyword cConstant FlowequationIsHOEnum
    163177syn keyword cConstant FlowequationIsL1L2Enum
    164 syn keyword cConstant FlowequationIsMLHOEnum
     178syn keyword cConstant FlowequationIsMOLHOEnum
    165179syn keyword cConstant FlowequationIsSIAEnum
    166180syn keyword cConstant FlowequationIsSSAEnum
     
    189203syn keyword cConstant GroundinglineMeltInterpolationEnum
    190204syn keyword cConstant GroundinglineMigrationEnum
     205syn keyword cConstant GroundinglineNumRequestedOutputsEnum
     206syn keyword cConstant GroundinglineRequestedOutputsEnum
    191207syn keyword cConstant HydrologyAveragingEnum
    192208syn keyword cConstant HydrologyCavitySpacingEnum
     
    263279syn keyword cConstant LockFileNameEnum
    264280syn keyword cConstant LoveAllowLayerDeletionEnum
     281syn keyword cConstant LoveChandlerWobbleEnum
    265282syn keyword cConstant LoveCoreMantleBoundaryEnum
    266283syn keyword cConstant LoveEarthMassEnum
     
    283300syn keyword cConstant LoveStartingLayerEnum
    284301syn keyword cConstant LoveUnderflowTolEnum
     302syn keyword cConstant LovePostWidderThresholdEnum
    285303syn keyword cConstant MassFluxSegmentsEnum
    286304syn keyword cConstant MassFluxSegmentsPresentEnum
     
    352370syn keyword cConstant ModelnameEnum
    353371syn keyword cConstant SamplingAlphaEnum
    354 syn keyword cConstant SamplingPhiEnum
    355372syn keyword cConstant SamplingNumRequestedOutputsEnum
    356373syn keyword cConstant SamplingRequestedOutputsEnum
    357374syn keyword cConstant SamplingRobinEnum
    358375syn keyword cConstant SamplingSeedEnum
    359 syn keyword cConstant SamplingTauEnum
    360376syn keyword cConstant SaveResultsEnum
    361377syn keyword cConstant SolidearthPartitionIceEnum
     
    369385syn keyword cConstant SolidearthSettingsAbstolEnum
    370386syn keyword cConstant SolidearthSettingsCrossSectionShapeEnum
    371 syn keyword cConstant RotationalAngularVelocityEnum
    372387syn keyword cConstant SolidearthSettingsElasticEnum
    373388syn keyword cConstant SolidearthSettingsViscousEnum
     
    376391syn keyword cConstant SealevelchangeViscousTimesEnum
    377392syn keyword cConstant SealevelchangeViscousIndexEnum
     393syn keyword cConstant SealevelchangeViscousPolarMotionEnum
     394syn keyword cConstant SealevelchangeRunCountEnum
     395syn keyword cConstant SealevelchangeTransitionsEnum
     396syn keyword cConstant SealevelchangeRequestedOutputsEnum
     397syn keyword cConstant RotationalAngularVelocityEnum
    378398syn keyword cConstant RotationalEquatorialMoiEnum
     399syn keyword cConstant RotationalPolarMoiEnum
     400syn keyword cConstant LovePolarMotionTransferFunctionColinearEnum
     401syn keyword cConstant LovePolarMotionTransferFunctionOrthogonalEnum
    379402syn keyword cConstant TidalLoveHEnum
    380403syn keyword cConstant TidalLoveKEnum
     
    388411syn keyword cConstant SealevelchangeGSelfAttractionEnum
    389412syn keyword cConstant SealevelchangeGViscoElasticEnum
     413syn keyword cConstant SealevelchangeUViscoElasticEnum
     414syn keyword cConstant SealevelchangeHViscoElasticEnum
     415syn keyword cConstant SealevelchangePolarMotionTransferFunctionColinearEnum
     416syn keyword cConstant SealevelchangePolarMotionTransferFunctionOrthogonalEnum
     417syn keyword cConstant SealevelchangePolarMotionTransferFunctionZEnum
     418syn keyword cConstant SealevelchangeTidalK2Enum
     419syn keyword cConstant SealevelchangeTidalH2Enum
     420syn keyword cConstant SealevelchangeTidalL2Enum
    390421syn keyword cConstant SolidearthSettingsSealevelLoadingEnum
    391422syn keyword cConstant SolidearthSettingsGRDEnum
    392423syn keyword cConstant SolidearthSettingsRunFrequencyEnum
    393424syn keyword cConstant SolidearthSettingsTimeAccEnum
    394 syn keyword cConstant SealevelchangeHViscoElasticEnum
    395425syn keyword cConstant SolidearthSettingsHorizEnum
    396426syn keyword cConstant SolidearthSettingsMaxiterEnum
     
    404434syn keyword cConstant StochasticForcingIsStochasticForcingEnum
    405435syn keyword cConstant StochasticForcingIsWaterPressureEnum
     436syn keyword cConstant StochasticForcingNoisetermsEnum
    406437syn keyword cConstant StochasticForcingNumFieldsEnum
    407438syn keyword cConstant StochasticForcingRandomflagEnum
    408 syn keyword cConstant RotationalPolarMoiEnum
     439syn keyword cConstant StochasticForcingTimestepEnum
    409440syn keyword cConstant SolidearthSettingsReltolEnum
    410 syn keyword cConstant SealevelchangeRequestedOutputsEnum
    411441syn keyword cConstant SolidearthSettingsSelfAttractionEnum
    412442syn keyword cConstant SolidearthSettingsRotationEnum
    413443syn keyword cConstant SolidearthSettingsMaxSHCoeffEnum
    414 syn keyword cConstant SealevelchangeRunCountEnum
    415 syn keyword cConstant SealevelchangeTransitionsEnum
    416 syn keyword cConstant SealevelchangeUViscoElasticEnum
    417444syn keyword cConstant SettingsIoGatherEnum
    418445syn keyword cConstant SettingsNumResultsOnNodesEnum
     
    439466syn keyword cConstant SmbDpermilEnum
    440467syn keyword cConstant SmbDsnowIdxEnum
     468syn keyword cConstant SmbElevationBinsEnum
    441469syn keyword cConstant SmbCldFracEnum
    442470syn keyword cConstant SmbDelta18oEnum
     
    466494syn keyword cConstant SmbIsturbulentfluxEnum
    467495syn keyword cConstant SmbKEnum
     496syn keyword cConstant SmbLapseRatesEnum
    468497syn keyword cConstant SmbNumBasinsEnum
     498syn keyword cConstant SmbNumElevationBinsEnum
    469499syn keyword cConstant SmbNumRequestedOutputsEnum
    470500syn keyword cConstant SmbPfacEnum
    471501syn keyword cConstant SmbPhiEnum
    472502syn keyword cConstant SmbRdlEnum
     503syn keyword cConstant SmbRefElevationEnum
    473504syn keyword cConstant SmbRequestedOutputsEnum
    474505syn keyword cConstant SmbRlapsEnum
     
    579610syn keyword cConstant BalancethicknessThickeningRateEnum
    580611syn keyword cConstant BasalCrevasseEnum
     612syn keyword cConstant BasalforcingsDeepwaterMeltingRateAutoregressionEnum
     613syn keyword cConstant BasalforcingsDeepwaterMeltingRateNoiseEnum
     614syn keyword cConstant BasalforcingsDeepwaterMeltingRateValuesAutoregressionEnum
    581615syn keyword cConstant BasalforcingsFloatingiceMeltingRateEnum
    582616syn keyword cConstant BasalforcingsGeothermalfluxEnum
    583617syn keyword cConstant BasalforcingsGroundediceMeltingRateEnum
     618syn keyword cConstant BasalforcingsLinearBasinIdEnum
    584619syn keyword cConstant BasalforcingsPerturbationMeltingRateEnum
     620syn keyword cConstant BasalforcingsSpatialDeepwaterElevationEnum
     621syn keyword cConstant BasalforcingsSpatialDeepwaterMeltingRateEnum
     622syn keyword cConstant BasalforcingsSpatialUpperwaterElevationEnum
     623syn keyword cConstant BasalforcingsSpatialUpperwaterMeltingRateEnum
    585624syn keyword cConstant BasalforcingsIsmip6BasinIdEnum
    586625syn keyword cConstant BasalforcingsIsmip6TfEnum
     
    604643syn keyword cConstant BaseSlopeYEnum
    605644syn keyword cConstant BaselineBasalforcingsFloatingiceMeltingRateEnum
     645syn keyword cConstant BaselineBasalforcingsSpatialDeepwaterMeltingRateEnum
    606646syn keyword cConstant BaselineCalvingCalvingrateEnum
    607647syn keyword cConstant BaselineFrictionEffectivePressureEnum
     648syn keyword cConstant BaselineSmbMassBalanceEnum
    608649syn keyword cConstant BedEnum
    609650syn keyword cConstant BedGRDEnum
     
    618659syn keyword cConstant CalvingCalvingrateEnum
    619660syn keyword cConstant CalvingHabFractionEnum
     661syn keyword cConstant CalvingAblationrateEnum
    620662syn keyword cConstant CalvingMeltingrateEnum
    621663syn keyword cConstant CalvingStressThresholdFloatingiceEnum
    622664syn keyword cConstant CalvingStressThresholdGroundediceEnum
    623665syn keyword cConstant CalvinglevermannCoeffEnum
    624 syn keyword cConstant CalvingratexAverageEnum
    625666syn keyword cConstant CalvingratexEnum
    626 syn keyword cConstant CalvingrateyAverageEnum
    627667syn keyword cConstant CalvingrateyEnum
    628668syn keyword cConstant CalvingFluxLevelsetEnum
     
    803843syn keyword cConstant RheologyBbarAbsGradientEnum
    804844syn keyword cConstant SampleEnum
     845syn keyword cConstant SampleOldEnum
     846syn keyword cConstant SampleNoiseEnum
    805847syn keyword cConstant SamplingBetaEnum
    806848syn keyword cConstant SamplingKappaEnum
     849syn keyword cConstant SamplingPhiEnum
     850syn keyword cConstant SamplingTauEnum
    807851syn keyword cConstant SealevelEnum
    808852syn keyword cConstant SealevelGRDEnum
     
    839883syn keyword cConstant BslcRateEnum
    840884syn keyword cConstant GmtslcEnum
    841 syn keyword cConstant SealevelGrotm1Enum
    842 syn keyword cConstant SealevelGrotm2Enum
    843 syn keyword cConstant SealevelGrotm3Enum
    844 syn keyword cConstant SealevelGUrotm1Enum
    845 syn keyword cConstant SealevelGUrotm2Enum
    846 syn keyword cConstant SealevelGUrotm3Enum
    847 syn keyword cConstant SealevelGNrotm1Enum
    848 syn keyword cConstant SealevelGNrotm2Enum
    849 syn keyword cConstant SealevelGNrotm3Enum
    850 syn keyword cConstant SealevelGErotm1Enum
    851 syn keyword cConstant SealevelGErotm2Enum
    852 syn keyword cConstant SealevelGErotm3Enum
    853885syn keyword cConstant SealevelRSLBarystaticEnum
    854886syn keyword cConstant SealevelRSLRateEnum
     
    862894syn keyword cConstant SealevelchangeGEEnum
    863895syn keyword cConstant SealevelchangeGNEnum
     896syn keyword cConstant SealevelchangeGrotEnum
     897syn keyword cConstant SealevelchangeGUrotEnum
     898syn keyword cConstant SealevelchangeGNrotEnum
     899syn keyword cConstant SealevelchangeGErotEnum
    864900syn keyword cConstant SealevelchangeGsubelOceanEnum
    865901syn keyword cConstant SealevelchangeGUsubelOceanEnum
     
    11951231syn keyword cConstant ArrheniusEnum
    11961232syn keyword cConstant AutodiffJacobianEnum
     1233syn keyword cConstant AutoregressionLinearFloatingMeltRateEnum
    11971234syn keyword cConstant Balancethickness2AnalysisEnum
    11981235syn keyword cConstant Balancethickness2SolutionEnum
     
    12181255syn keyword cConstant CalvingHabEnum
    12191256syn keyword cConstant CalvingLevermannEnum
     1257syn keyword cConstant CalvingTestEnum
     1258syn keyword cConstant CalvingParameterizationEnum
    12201259syn keyword cConstant CalvingVonmisesEnum
    12211260syn keyword cConstant CfdragcoeffabsgradEnum
     
    13461385syn keyword cConstant JEnum
    13471386syn keyword cConstant L1L2ApproximationEnum
    1348 syn keyword cConstant MLHOApproximationEnum
     1387syn keyword cConstant MOLHOApproximationEnum
    13491388syn keyword cConstant L2ProjectionBaseAnalysisEnum
    13501389syn keyword cConstant L2ProjectionEPLAnalysisEnum
     
    13581397syn keyword cConstant LoadsEnum
    13591398syn keyword cConstant LoveAnalysisEnum
    1360 syn keyword cConstant LoveHiEnum
    1361 syn keyword cConstant LoveHrEnum
     1399syn keyword cConstant LoveHfEnum
     1400syn keyword cConstant LoveHtEnum
    13621401syn keyword cConstant LoveKernelsImagEnum
    13631402syn keyword cConstant LoveKernelsRealEnum
    1364 syn keyword cConstant LoveKiEnum
    1365 syn keyword cConstant LoveKrEnum
    1366 syn keyword cConstant LoveLiEnum
    1367 syn keyword cConstant LoveLrEnum
     1403syn keyword cConstant LoveKfEnum
     1404syn keyword cConstant LoveKtEnum
     1405syn keyword cConstant LoveLfEnum
     1406syn keyword cConstant LoveLtEnum
     1407syn keyword cConstant LoveTidalHtEnum
     1408syn keyword cConstant LoveTidalKtEnum
     1409syn keyword cConstant LoveTidalLtEnum
     1410syn keyword cConstant LovePMTF1tEnum
     1411syn keyword cConstant LovePMTF2tEnum
    13681412syn keyword cConstant LoveSolutionEnum
    13691413syn keyword cConstant MINIEnum
     
    14771521syn keyword cConstant SealevelAbsoluteEnum
    14781522syn keyword cConstant SealevelEmotionEnum
    1479 syn keyword cConstant SealevelInertiaTensorXZEnum
    1480 syn keyword cConstant SealevelInertiaTensorYZEnum
    1481 syn keyword cConstant SealevelInertiaTensorZZEnum
     1523syn keyword cConstant SealevelchangePolarMotionXEnum
     1524syn keyword cConstant SealevelchangePolarMotionYEnum
     1525syn keyword cConstant SealevelchangePolarMotionZEnum
    14821526syn keyword cConstant SealevelchangePolarMotionEnum
    14831527syn keyword cConstant SealevelNmotionEnum
     
    15801624syn keyword cType Cfsurfacesquare
    15811625syn keyword cType Channel
    1582 syn keyword cType classes
    15831626syn keyword cType Constraint
    15841627syn keyword cType Constraints
     
    15871630syn keyword cType ControlInput
    15881631syn keyword cType Covertree
     1632syn keyword cType DataSetParam
    15891633syn keyword cType DatasetInput
    1590 syn keyword cType DataSetParam
    15911634syn keyword cType Definition
    15921635syn keyword cType DependentObject
     
    16011644syn keyword cType ElementInput
    16021645syn keyword cType ElementMatrix
     1646syn keyword cType ElementVector
    16031647syn keyword cType Elements
    1604 syn keyword cType ElementVector
    16051648syn keyword cType ExponentialVariogram
    16061649syn keyword cType ExternalResult
     
    16091652syn keyword cType Friction
    16101653syn keyword cType Gauss
    1611 syn keyword cType GaussianVariogram
    1612 syn keyword cType gaussobjects
    16131654syn keyword cType GaussPenta
    16141655syn keyword cType GaussSeg
    16151656syn keyword cType GaussTetra
    16161657syn keyword cType GaussTria
     1658syn keyword cType GaussianVariogram
    16171659syn keyword cType GenericExternalResult
    16181660syn keyword cType GenericOption
     
    16301672syn keyword cType IssmDirectApplicInterface
    16311673syn keyword cType IssmParallelDirectApplicInterface
    1632 syn keyword cType krigingobjects
    16331674syn keyword cType Load
    16341675syn keyword cType Loads
     
    16411682syn keyword cType Matice
    16421683syn keyword cType Matlitho
    1643 syn keyword cType matrixobjects
    16441684syn keyword cType MatrixParam
    16451685syn keyword cType Misfit
     
    16541694syn keyword cType Observations
    16551695syn keyword cType Option
     1696syn keyword cType OptionUtilities
    16561697syn keyword cType Options
    1657 syn keyword cType OptionUtilities
    16581698syn keyword cType Param
    16591699syn keyword cType Parameters
     
    16691709syn keyword cType Regionaloutput
    16701710syn keyword cType Results
     1711syn keyword cType RiftStruct
    16711712syn keyword cType Riftfront
    1672 syn keyword cType RiftStruct
    16731713syn keyword cType SealevelGeometry
    16741714syn keyword cType Seg
    16751715syn keyword cType SegInput
     1716syn keyword cType SegRef
    16761717syn keyword cType Segment
    1677 syn keyword cType SegRef
    16781718syn keyword cType SpcDynamic
    16791719syn keyword cType SpcStatic
     
    16941734syn keyword cType Vertex
    16951735syn keyword cType Vertices
     1736syn keyword cType classes
     1737syn keyword cType gaussobjects
     1738syn keyword cType krigingobjects
     1739syn keyword cType matrixobjects
    16961740syn keyword cType AdjointBalancethickness2Analysis
    16971741syn keyword cType AdjointBalancethicknessAnalysis
  • issm/trunk/src/c/shared/Enum/EnumDefinitions.h

    r26744 r27035  
    5858        BalancethicknessStabilizationEnum,
    5959        BarystaticContributionsEnum,
     60        BasalforcingsAutoregressionInitialTimeEnum,
     61        BasalforcingsAutoregressionTimestepEnum,
     62        BasalforcingsAutoregressiveOrderEnum,
     63        BasalforcingsBeta0Enum,
     64        BasalforcingsBeta1Enum,
    6065        BasalforcingsBottomplumedepthEnum,
    6166        BasalforcingsCrustthicknessEnum,
     
    7176        BasalforcingsIsmip6NumBasinsEnum,
    7277        BasalforcingsIsmip6TfDepthsEnum,
     78        BasalforcingsLinearNumBasinsEnum,
    7379        BasalforcingsLowercrustheatEnum,
    7480        BasalforcingsMantleconductivityEnum,
    7581        BasalforcingsNusseltEnum,
     82        BasalforcingsPhiEnum,
    7683        BasalforcingsPicoAverageOverturningEnum,
    7784        BasalforcingsPicoAverageSalinityEnum,
     
    99106        CalvingLawEnum,
    100107        CalvingMinthicknessEnum,
     108        CalvingTestSpeedfactorEnum,
     109        CalvingTestIndependentRateEnum,
     110        CalvingUseParamEnum,
     111        CalvingScaleThetaEnum,
     112        CalvingAmpAlphaEnum,
     113        CalvingMidpointEnum,
     114        CalvingNonlinearLawEnum,
    101115        ConfigurationTypeEnum,
    102116        ConstantsGEnum,
     
    156170        FlowequationIsHOEnum,
    157171        FlowequationIsL1L2Enum,
    158         FlowequationIsMLHOEnum,
     172        FlowequationIsMOLHOEnum,
    159173        FlowequationIsSIAEnum,
    160174        FlowequationIsSSAEnum,
     
    183197        GroundinglineMeltInterpolationEnum,
    184198        GroundinglineMigrationEnum,
     199        GroundinglineNumRequestedOutputsEnum,
     200        GroundinglineRequestedOutputsEnum,
    185201        HydrologyAveragingEnum,
    186202        HydrologyCavitySpacingEnum,
     
    257273        LockFileNameEnum,
    258274        LoveAllowLayerDeletionEnum,
     275        LoveChandlerWobbleEnum,
    259276        LoveCoreMantleBoundaryEnum,
    260277        LoveEarthMassEnum,
     
    277294        LoveStartingLayerEnum,
    278295        LoveUnderflowTolEnum,
     296        LovePostWidderThresholdEnum,
    279297        MassFluxSegmentsEnum,
    280298        MassFluxSegmentsPresentEnum,
     
    346364        ModelnameEnum,
    347365        SamplingAlphaEnum,
    348         SamplingPhiEnum,
    349366        SamplingNumRequestedOutputsEnum,
    350367        SamplingRequestedOutputsEnum,
    351368        SamplingRobinEnum,
    352369        SamplingSeedEnum,
    353         SamplingTauEnum,
    354370        SaveResultsEnum,
    355371        SolidearthPartitionIceEnum,
     
    363379        SolidearthSettingsAbstolEnum,
    364380        SolidearthSettingsCrossSectionShapeEnum,
    365         RotationalAngularVelocityEnum,
    366381        SolidearthSettingsElasticEnum,
    367382        SolidearthSettingsViscousEnum,
     
    370385        SealevelchangeViscousTimesEnum,
    371386        SealevelchangeViscousIndexEnum,
     387        SealevelchangeViscousPolarMotionEnum,
     388        SealevelchangeRunCountEnum,
     389        SealevelchangeTransitionsEnum,
     390        SealevelchangeRequestedOutputsEnum,
     391        RotationalAngularVelocityEnum,
    372392        RotationalEquatorialMoiEnum,
     393        RotationalPolarMoiEnum,
     394        LovePolarMotionTransferFunctionColinearEnum,
     395        LovePolarMotionTransferFunctionOrthogonalEnum,
    373396        TidalLoveHEnum,
    374397        TidalLoveKEnum,
     
    382405        SealevelchangeGSelfAttractionEnum,
    383406        SealevelchangeGViscoElasticEnum,
     407        SealevelchangeUViscoElasticEnum,
     408        SealevelchangeHViscoElasticEnum,
     409        SealevelchangePolarMotionTransferFunctionColinearEnum,
     410        SealevelchangePolarMotionTransferFunctionOrthogonalEnum,
     411        SealevelchangePolarMotionTransferFunctionZEnum,
     412        SealevelchangeTidalK2Enum,
     413        SealevelchangeTidalH2Enum,
     414        SealevelchangeTidalL2Enum,
    384415        SolidearthSettingsSealevelLoadingEnum,
    385416        SolidearthSettingsGRDEnum,
    386417        SolidearthSettingsRunFrequencyEnum,
    387418        SolidearthSettingsTimeAccEnum,
    388         SealevelchangeHViscoElasticEnum,
    389419        SolidearthSettingsHorizEnum,
    390420        SolidearthSettingsMaxiterEnum,
     
    398428        StochasticForcingIsStochasticForcingEnum,
    399429        StochasticForcingIsWaterPressureEnum,
     430        StochasticForcingNoisetermsEnum,
    400431        StochasticForcingNumFieldsEnum,
    401432        StochasticForcingRandomflagEnum,
    402         RotationalPolarMoiEnum,
     433        StochasticForcingTimestepEnum,
    403434        SolidearthSettingsReltolEnum,
    404         SealevelchangeRequestedOutputsEnum,
    405435        SolidearthSettingsSelfAttractionEnum,
    406436        SolidearthSettingsRotationEnum,
    407437        SolidearthSettingsMaxSHCoeffEnum,
    408         SealevelchangeRunCountEnum,
    409         SealevelchangeTransitionsEnum,
    410         SealevelchangeUViscoElasticEnum,
    411438        SettingsIoGatherEnum,
    412439        SettingsNumResultsOnNodesEnum,
     
    433460        SmbDpermilEnum,
    434461        SmbDsnowIdxEnum,
     462   SmbElevationBinsEnum,
    435463        SmbCldFracEnum,
    436464        SmbDelta18oEnum,
     
    460488        SmbIsturbulentfluxEnum,
    461489        SmbKEnum,
     490   SmbLapseRatesEnum,
    462491        SmbNumBasinsEnum,
     492        SmbNumElevationBinsEnum,
    463493        SmbNumRequestedOutputsEnum,
    464494        SmbPfacEnum,
    465495        SmbPhiEnum,
    466496        SmbRdlEnum,
     497        SmbRefElevationEnum,
    467498        SmbRequestedOutputsEnum,
    468499        SmbRlapsEnum,
     
    534565        TransientIsgroundinglineEnum,
    535566        TransientIshydrologyEnum,
    536         TransientIsmasstransportEnum, 
     567        TransientIsmasstransportEnum,
    537568        TransientIsoceantransportEnum,
    538569        TransientIsmovingfrontEnum,
     
    575606        BalancethicknessThickeningRateEnum,
    576607        BasalCrevasseEnum,
     608        BasalforcingsDeepwaterMeltingRateAutoregressionEnum,
     609        BasalforcingsDeepwaterMeltingRateNoiseEnum,
     610        BasalforcingsDeepwaterMeltingRateValuesAutoregressionEnum,
    577611        BasalforcingsFloatingiceMeltingRateEnum,
    578612        BasalforcingsGeothermalfluxEnum,
    579613        BasalforcingsGroundediceMeltingRateEnum,
     614        BasalforcingsLinearBasinIdEnum,
    580615        BasalforcingsPerturbationMeltingRateEnum,
     616        BasalforcingsSpatialDeepwaterElevationEnum,
     617        BasalforcingsSpatialDeepwaterMeltingRateEnum,
     618        BasalforcingsSpatialUpperwaterElevationEnum,
     619        BasalforcingsSpatialUpperwaterMeltingRateEnum,
    581620        BasalforcingsIsmip6BasinIdEnum,
    582621        BasalforcingsIsmip6TfEnum,
     
    600639        BaseSlopeYEnum,
    601640        BaselineBasalforcingsFloatingiceMeltingRateEnum,
     641        BaselineBasalforcingsSpatialDeepwaterMeltingRateEnum,
    602642        BaselineCalvingCalvingrateEnum,
    603643        BaselineFrictionEffectivePressureEnum,
     644        BaselineSmbMassBalanceEnum,
    604645        BedEnum,
    605646        BedGRDEnum,
     
    614655        CalvingCalvingrateEnum,
    615656        CalvingHabFractionEnum,
     657        CalvingAblationrateEnum,
    616658        CalvingMeltingrateEnum,
    617659        CalvingStressThresholdFloatingiceEnum,
    618660        CalvingStressThresholdGroundediceEnum,
    619661        CalvinglevermannCoeffEnum,
    620         CalvingratexAverageEnum,
    621662        CalvingratexEnum,
    622         CalvingrateyAverageEnum,
    623663        CalvingrateyEnum,
    624664        CalvingFluxLevelsetEnum,
     
    799839        RheologyBbarAbsGradientEnum,
    800840        SampleEnum,
     841        SampleOldEnum,
     842        SampleNoiseEnum,
    801843        SamplingBetaEnum,
    802844        SamplingKappaEnum,
     845        SamplingPhiEnum,
     846        SamplingTauEnum,
    803847        SealevelEnum,
    804848        SealevelGRDEnum,
     
    835879        BslcRateEnum,
    836880        GmtslcEnum,
    837         SealevelGrotm1Enum,
    838         SealevelGrotm2Enum,
    839         SealevelGrotm3Enum,
    840         SealevelGUrotm1Enum,
    841         SealevelGUrotm2Enum,
    842         SealevelGUrotm3Enum,
    843         SealevelGNrotm1Enum,
    844         SealevelGNrotm2Enum,
    845         SealevelGNrotm3Enum,
    846         SealevelGErotm1Enum,
    847         SealevelGErotm2Enum,
    848         SealevelGErotm3Enum,
    849881        SealevelRSLBarystaticEnum,
    850882        SealevelRSLRateEnum,
     
    858890        SealevelchangeGEEnum,
    859891        SealevelchangeGNEnum,
     892        SealevelchangeGrotEnum,
     893        SealevelchangeGUrotEnum,
     894        SealevelchangeGNrotEnum,
     895        SealevelchangeGErotEnum,
    860896        SealevelchangeGsubelOceanEnum,
    861897        SealevelchangeGUsubelOceanEnum,
     
    10361072        TemperatureSEMICEnum,
    10371073   ThermalforcingAutoregressionNoiseEnum,
    1038         ThermalforcingValuesAutoregressionEnum, 
     1074        ThermalforcingValuesAutoregressionEnum,
    10391075        ThermalSpctemperatureEnum,
    10401076        ThicknessAbsGradientEnum,
     
    11941230        ArrheniusEnum,
    11951231        AutodiffJacobianEnum,
     1232        AutoregressionLinearFloatingMeltRateEnum,
    11961233        Balancethickness2AnalysisEnum,
    11971234        Balancethickness2SolutionEnum,
     
    12171254        CalvingHabEnum,
    12181255        CalvingLevermannEnum,
     1256        CalvingTestEnum,
     1257        CalvingParameterizationEnum,
    12191258        CalvingVonmisesEnum,
    12201259        CfdragcoeffabsgradEnum,
     
    13451384        JEnum,
    13461385        L1L2ApproximationEnum,
    1347         MLHOApproximationEnum,
     1386        MOLHOApproximationEnum,
    13481387        L2ProjectionBaseAnalysisEnum,
    13491388        L2ProjectionEPLAnalysisEnum,
     
    13571396        LoadsEnum,
    13581397        LoveAnalysisEnum,
    1359         LoveHiEnum,
    1360         LoveHrEnum,
     1398        LoveHfEnum,
     1399        LoveHtEnum,
    13611400        LoveKernelsImagEnum,
    13621401        LoveKernelsRealEnum,
    1363         LoveKiEnum,
    1364         LoveKrEnum,
    1365         LoveLiEnum,
    1366         LoveLrEnum,
     1402        LoveKfEnum,
     1403        LoveKtEnum,
     1404        LoveLfEnum,
     1405        LoveLtEnum,
     1406        LoveTidalHtEnum,
     1407        LoveTidalKtEnum,
     1408        LoveTidalLtEnum,
     1409        LovePMTF1tEnum,
     1410        LovePMTF2tEnum,
    13671411        LoveSolutionEnum,
    13681412        MINIEnum,
     
    14761520        SealevelAbsoluteEnum,
    14771521        SealevelEmotionEnum,
    1478         SealevelInertiaTensorXZEnum,
    1479         SealevelInertiaTensorYZEnum,
    1480         SealevelInertiaTensorZZEnum,
     1522        SealevelchangePolarMotionXEnum,
     1523        SealevelchangePolarMotionYEnum,
     1524        SealevelchangePolarMotionZEnum,
    14811525        SealevelchangePolarMotionEnum,
    14821526        SealevelNmotionEnum,
  • issm/trunk/src/c/shared/Enum/EnumToStringx.cpp

    r26744 r27035  
    6666                case BalancethicknessStabilizationEnum : return "BalancethicknessStabilization";
    6767                case BarystaticContributionsEnum : return "BarystaticContributions";
     68                case BasalforcingsAutoregressionInitialTimeEnum : return "BasalforcingsAutoregressionInitialTime";
     69                case BasalforcingsAutoregressionTimestepEnum : return "BasalforcingsAutoregressionTimestep";
     70                case BasalforcingsAutoregressiveOrderEnum : return "BasalforcingsAutoregressiveOrder";
     71                case BasalforcingsBeta0Enum : return "BasalforcingsBeta0";
     72                case BasalforcingsBeta1Enum : return "BasalforcingsBeta1";
    6873                case BasalforcingsBottomplumedepthEnum : return "BasalforcingsBottomplumedepth";
    6974                case BasalforcingsCrustthicknessEnum : return "BasalforcingsCrustthickness";
     
    7984                case BasalforcingsIsmip6NumBasinsEnum : return "BasalforcingsIsmip6NumBasins";
    8085                case BasalforcingsIsmip6TfDepthsEnum : return "BasalforcingsIsmip6TfDepths";
     86                case BasalforcingsLinearNumBasinsEnum : return "BasalforcingsLinearNumBasins";
    8187                case BasalforcingsLowercrustheatEnum : return "BasalforcingsLowercrustheat";
    8288                case BasalforcingsMantleconductivityEnum : return "BasalforcingsMantleconductivity";
    8389                case BasalforcingsNusseltEnum : return "BasalforcingsNusselt";
     90                case BasalforcingsPhiEnum : return "BasalforcingsPhi";
    8491                case BasalforcingsPicoAverageOverturningEnum : return "BasalforcingsPicoAverageOverturning";
    8592                case BasalforcingsPicoAverageSalinityEnum : return "BasalforcingsPicoAverageSalinity";
     
    107114                case CalvingLawEnum : return "CalvingLaw";
    108115                case CalvingMinthicknessEnum : return "CalvingMinthickness";
     116                case CalvingTestSpeedfactorEnum : return "CalvingTestSpeedfactor";
     117                case CalvingTestIndependentRateEnum : return "CalvingTestIndependentRate";
     118                case CalvingUseParamEnum : return "CalvingUseParam";
     119                case CalvingScaleThetaEnum : return "CalvingScaleTheta";
     120                case CalvingAmpAlphaEnum : return "CalvingAmpAlpha";
     121                case CalvingMidpointEnum : return "CalvingMidpoint";
     122                case CalvingNonlinearLawEnum : return "CalvingNonlinearLaw";
    109123                case ConfigurationTypeEnum : return "ConfigurationType";
    110124                case ConstantsGEnum : return "ConstantsG";
     
    164178                case FlowequationIsHOEnum : return "FlowequationIsHO";
    165179                case FlowequationIsL1L2Enum : return "FlowequationIsL1L2";
    166                 case FlowequationIsMLHOEnum : return "FlowequationIsMLHO";
     180                case FlowequationIsMOLHOEnum : return "FlowequationIsMOLHO";
    167181                case FlowequationIsSIAEnum : return "FlowequationIsSIA";
    168182                case FlowequationIsSSAEnum : return "FlowequationIsSSA";
     
    191205                case GroundinglineMeltInterpolationEnum : return "GroundinglineMeltInterpolation";
    192206                case GroundinglineMigrationEnum : return "GroundinglineMigration";
     207                case GroundinglineNumRequestedOutputsEnum : return "GroundinglineNumRequestedOutputs";
     208                case GroundinglineRequestedOutputsEnum : return "GroundinglineRequestedOutputs";
    193209                case HydrologyAveragingEnum : return "HydrologyAveraging";
    194210                case HydrologyCavitySpacingEnum : return "HydrologyCavitySpacing";
     
    265281                case LockFileNameEnum : return "LockFileName";
    266282                case LoveAllowLayerDeletionEnum : return "LoveAllowLayerDeletion";
     283                case LoveChandlerWobbleEnum : return "LoveChandlerWobble";
    267284                case LoveCoreMantleBoundaryEnum : return "LoveCoreMantleBoundary";
    268285                case LoveEarthMassEnum : return "LoveEarthMass";
     
    285302                case LoveStartingLayerEnum : return "LoveStartingLayer";
    286303                case LoveUnderflowTolEnum : return "LoveUnderflowTol";
     304                case LovePostWidderThresholdEnum : return "LovePostWidderThreshold";
    287305                case MassFluxSegmentsEnum : return "MassFluxSegments";
    288306                case MassFluxSegmentsPresentEnum : return "MassFluxSegmentsPresent";
     
    354372                case ModelnameEnum : return "Modelname";
    355373                case SamplingAlphaEnum : return "SamplingAlpha";
    356                 case SamplingPhiEnum : return "SamplingPhi";
    357374                case SamplingNumRequestedOutputsEnum : return "SamplingNumRequestedOutputs";
    358375                case SamplingRequestedOutputsEnum : return "SamplingRequestedOutputs";
    359376                case SamplingRobinEnum : return "SamplingRobin";
    360377                case SamplingSeedEnum : return "SamplingSeed";
    361                 case SamplingTauEnum : return "SamplingTau";
    362378                case SaveResultsEnum : return "SaveResults";
    363379                case SolidearthPartitionIceEnum : return "SolidearthPartitionIce";
     
    371387                case SolidearthSettingsAbstolEnum : return "SolidearthSettingsAbstol";
    372388                case SolidearthSettingsCrossSectionShapeEnum : return "SolidearthSettingsCrossSectionShape";
    373                 case RotationalAngularVelocityEnum : return "RotationalAngularVelocity";
    374389                case SolidearthSettingsElasticEnum : return "SolidearthSettingsElastic";
    375390                case SolidearthSettingsViscousEnum : return "SolidearthSettingsViscous";
     
    378393                case SealevelchangeViscousTimesEnum : return "SealevelchangeViscousTimes";
    379394                case SealevelchangeViscousIndexEnum : return "SealevelchangeViscousIndex";
     395                case SealevelchangeViscousPolarMotionEnum : return "SealevelchangeViscousPolarMotion";
     396                case SealevelchangeRunCountEnum : return "SealevelchangeRunCount";
     397                case SealevelchangeTransitionsEnum : return "SealevelchangeTransitions";
     398                case SealevelchangeRequestedOutputsEnum : return "SealevelchangeRequestedOutputs";
     399                case RotationalAngularVelocityEnum : return "RotationalAngularVelocity";
    380400                case RotationalEquatorialMoiEnum : return "RotationalEquatorialMoi";
     401                case RotationalPolarMoiEnum : return "RotationalPolarMoi";
     402                case LovePolarMotionTransferFunctionColinearEnum : return "LovePolarMotionTransferFunctionColinear";
     403                case LovePolarMotionTransferFunctionOrthogonalEnum : return "LovePolarMotionTransferFunctionOrthogonal";
    381404                case TidalLoveHEnum : return "TidalLoveH";
    382405                case TidalLoveKEnum : return "TidalLoveK";
     
    390413                case SealevelchangeGSelfAttractionEnum : return "SealevelchangeGSelfAttraction";
    391414                case SealevelchangeGViscoElasticEnum : return "SealevelchangeGViscoElastic";
     415                case SealevelchangeUViscoElasticEnum : return "SealevelchangeUViscoElastic";
     416                case SealevelchangeHViscoElasticEnum : return "SealevelchangeHViscoElastic";
     417                case SealevelchangePolarMotionTransferFunctionColinearEnum : return "SealevelchangePolarMotionTransferFunctionColinear";
     418                case SealevelchangePolarMotionTransferFunctionOrthogonalEnum : return "SealevelchangePolarMotionTransferFunctionOrthogonal";
     419                case SealevelchangePolarMotionTransferFunctionZEnum : return "SealevelchangePolarMotionTransferFunctionZ";
     420                case SealevelchangeTidalK2Enum : return "SealevelchangeTidalK2";
     421                case SealevelchangeTidalH2Enum : return "SealevelchangeTidalH2";
     422                case SealevelchangeTidalL2Enum : return "SealevelchangeTidalL2";
    392423                case SolidearthSettingsSealevelLoadingEnum : return "SolidearthSettingsSealevelLoading";
    393424                case SolidearthSettingsGRDEnum : return "SolidearthSettingsGRD";
    394425                case SolidearthSettingsRunFrequencyEnum : return "SolidearthSettingsRunFrequency";
    395426                case SolidearthSettingsTimeAccEnum : return "SolidearthSettingsTimeAcc";
    396                 case SealevelchangeHViscoElasticEnum : return "SealevelchangeHViscoElastic";
    397427                case SolidearthSettingsHorizEnum : return "SolidearthSettingsHoriz";
    398428                case SolidearthSettingsMaxiterEnum : return "SolidearthSettingsMaxiter";
     
    406436                case StochasticForcingIsStochasticForcingEnum : return "StochasticForcingIsStochasticForcing";
    407437                case StochasticForcingIsWaterPressureEnum : return "StochasticForcingIsWaterPressure";
     438                case StochasticForcingNoisetermsEnum : return "StochasticForcingNoiseterms";
    408439                case StochasticForcingNumFieldsEnum : return "StochasticForcingNumFields";
    409440                case StochasticForcingRandomflagEnum : return "StochasticForcingRandomflag";
    410                 case RotationalPolarMoiEnum : return "RotationalPolarMoi";
     441                case StochasticForcingTimestepEnum : return "StochasticForcingTimestep";
    411442                case SolidearthSettingsReltolEnum : return "SolidearthSettingsReltol";
    412                 case SealevelchangeRequestedOutputsEnum : return "SealevelchangeRequestedOutputs";
    413443                case SolidearthSettingsSelfAttractionEnum : return "SolidearthSettingsSelfAttraction";
    414444                case SolidearthSettingsRotationEnum : return "SolidearthSettingsRotation";
    415445                case SolidearthSettingsMaxSHCoeffEnum : return "SolidearthSettingsMaxSHCoeff";
    416                 case SealevelchangeRunCountEnum : return "SealevelchangeRunCount";
    417                 case SealevelchangeTransitionsEnum : return "SealevelchangeTransitions";
    418                 case SealevelchangeUViscoElasticEnum : return "SealevelchangeUViscoElastic";
    419446                case SettingsIoGatherEnum : return "SettingsIoGather";
    420447                case SettingsNumResultsOnNodesEnum : return "SettingsNumResultsOnNodes";
     
    441468                case SmbDpermilEnum : return "SmbDpermil";
    442469                case SmbDsnowIdxEnum : return "SmbDsnowIdx";
     470                case SmbElevationBinsEnum : return "SmbElevationBins";
    443471                case SmbCldFracEnum : return "SmbCldFrac";
    444472                case SmbDelta18oEnum : return "SmbDelta18o";
     
    468496                case SmbIsturbulentfluxEnum : return "SmbIsturbulentflux";
    469497                case SmbKEnum : return "SmbK";
     498                case SmbLapseRatesEnum : return "SmbLapseRates";
    470499                case SmbNumBasinsEnum : return "SmbNumBasins";
     500                case SmbNumElevationBinsEnum : return "SmbNumElevationBins";
    471501                case SmbNumRequestedOutputsEnum : return "SmbNumRequestedOutputs";
    472502                case SmbPfacEnum : return "SmbPfac";
    473503                case SmbPhiEnum : return "SmbPhi";
    474504                case SmbRdlEnum : return "SmbRdl";
     505                case SmbRefElevationEnum : return "SmbRefElevation";
    475506                case SmbRequestedOutputsEnum : return "SmbRequestedOutputs";
    476507                case SmbRlapsEnum : return "SmbRlaps";
     
    581612                case BalancethicknessThickeningRateEnum : return "BalancethicknessThickeningRate";
    582613                case BasalCrevasseEnum : return "BasalCrevasse";
     614                case BasalforcingsDeepwaterMeltingRateAutoregressionEnum : return "BasalforcingsDeepwaterMeltingRateAutoregression";
     615                case BasalforcingsDeepwaterMeltingRateNoiseEnum : return "BasalforcingsDeepwaterMeltingRateNoise";
     616                case BasalforcingsDeepwaterMeltingRateValuesAutoregressionEnum : return "BasalforcingsDeepwaterMeltingRateValuesAutoregression";
    583617                case BasalforcingsFloatingiceMeltingRateEnum : return "BasalforcingsFloatingiceMeltingRate";
    584618                case BasalforcingsGeothermalfluxEnum : return "BasalforcingsGeothermalflux";
    585619                case BasalforcingsGroundediceMeltingRateEnum : return "BasalforcingsGroundediceMeltingRate";
     620                case BasalforcingsLinearBasinIdEnum : return "BasalforcingsLinearBasinId";
    586621                case BasalforcingsPerturbationMeltingRateEnum : return "BasalforcingsPerturbationMeltingRate";
     622                case BasalforcingsSpatialDeepwaterElevationEnum : return "BasalforcingsSpatialDeepwaterElevation";
     623                case BasalforcingsSpatialDeepwaterMeltingRateEnum : return "BasalforcingsSpatialDeepwaterMeltingRate";
     624                case BasalforcingsSpatialUpperwaterElevationEnum : return "BasalforcingsSpatialUpperwaterElevation";
     625                case BasalforcingsSpatialUpperwaterMeltingRateEnum : return "BasalforcingsSpatialUpperwaterMeltingRate";
    587626                case BasalforcingsIsmip6BasinIdEnum : return "BasalforcingsIsmip6BasinId";
    588627                case BasalforcingsIsmip6TfEnum : return "BasalforcingsIsmip6Tf";
     
    606645                case BaseSlopeYEnum : return "BaseSlopeY";
    607646                case BaselineBasalforcingsFloatingiceMeltingRateEnum : return "BaselineBasalforcingsFloatingiceMeltingRate";
     647                case BaselineBasalforcingsSpatialDeepwaterMeltingRateEnum : return "BaselineBasalforcingsSpatialDeepwaterMeltingRate";
    608648                case BaselineCalvingCalvingrateEnum : return "BaselineCalvingCalvingrate";
    609649                case BaselineFrictionEffectivePressureEnum : return "BaselineFrictionEffectivePressure";
     650                case BaselineSmbMassBalanceEnum : return "BaselineSmbMassBalance";
    610651                case BedEnum : return "Bed";
    611652                case BedGRDEnum : return "BedGRD";
     
    620661                case CalvingCalvingrateEnum : return "CalvingCalvingrate";
    621662                case CalvingHabFractionEnum : return "CalvingHabFraction";
     663                case CalvingAblationrateEnum : return "CalvingAblationrate";
    622664                case CalvingMeltingrateEnum : return "CalvingMeltingrate";
    623665                case CalvingStressThresholdFloatingiceEnum : return "CalvingStressThresholdFloatingice";
    624666                case CalvingStressThresholdGroundediceEnum : return "CalvingStressThresholdGroundedice";
    625667                case CalvinglevermannCoeffEnum : return "CalvinglevermannCoeff";
    626                 case CalvingratexAverageEnum : return "CalvingratexAverage";
    627668                case CalvingratexEnum : return "Calvingratex";
    628                 case CalvingrateyAverageEnum : return "CalvingrateyAverage";
    629669                case CalvingrateyEnum : return "Calvingratey";
    630670                case CalvingFluxLevelsetEnum : return "CalvingFluxLevelset";
     
    805845                case RheologyBbarAbsGradientEnum : return "RheologyBbarAbsGradient";
    806846                case SampleEnum : return "Sample";
     847                case SampleOldEnum : return "SampleOld";
     848                case SampleNoiseEnum : return "SampleNoise";
    807849                case SamplingBetaEnum : return "SamplingBeta";
    808850                case SamplingKappaEnum : return "SamplingKappa";
     851                case SamplingPhiEnum : return "SamplingPhi";
     852                case SamplingTauEnum : return "SamplingTau";
    809853                case SealevelEnum : return "Sealevel";
    810854                case SealevelGRDEnum : return "SealevelGRD";
     
    841885                case BslcRateEnum : return "BslcRate";
    842886                case GmtslcEnum : return "Gmtslc";
    843                 case SealevelGrotm1Enum : return "SealevelGrotm1";
    844                 case SealevelGrotm2Enum : return "SealevelGrotm2";
    845                 case SealevelGrotm3Enum : return "SealevelGrotm3";
    846                 case SealevelGUrotm1Enum : return "SealevelGUrotm1";
    847                 case SealevelGUrotm2Enum : return "SealevelGUrotm2";
    848                 case SealevelGUrotm3Enum : return "SealevelGUrotm3";
    849                 case SealevelGNrotm1Enum : return "SealevelGNrotm1";
    850                 case SealevelGNrotm2Enum : return "SealevelGNrotm2";
    851                 case SealevelGNrotm3Enum : return "SealevelGNrotm3";
    852                 case SealevelGErotm1Enum : return "SealevelGErotm1";
    853                 case SealevelGErotm2Enum : return "SealevelGErotm2";
    854                 case SealevelGErotm3Enum : return "SealevelGErotm3";
    855887                case SealevelRSLBarystaticEnum : return "SealevelRSLBarystatic";
    856888                case SealevelRSLRateEnum : return "SealevelRSLRate";
     
    864896                case SealevelchangeGEEnum : return "SealevelchangeGE";
    865897                case SealevelchangeGNEnum : return "SealevelchangeGN";
     898                case SealevelchangeGrotEnum : return "SealevelchangeGrot";
     899                case SealevelchangeGUrotEnum : return "SealevelchangeGUrot";
     900                case SealevelchangeGNrotEnum : return "SealevelchangeGNrot";
     901                case SealevelchangeGErotEnum : return "SealevelchangeGErot";
    866902                case SealevelchangeGsubelOceanEnum : return "SealevelchangeGsubelOcean";
    867903                case SealevelchangeGUsubelOceanEnum : return "SealevelchangeGUsubelOcean";
     
    11971233                case ArrheniusEnum : return "Arrhenius";
    11981234                case AutodiffJacobianEnum : return "AutodiffJacobian";
     1235                case AutoregressionLinearFloatingMeltRateEnum : return "AutoregressionLinearFloatingMeltRate";
    11991236                case Balancethickness2AnalysisEnum : return "Balancethickness2Analysis";
    12001237                case Balancethickness2SolutionEnum : return "Balancethickness2Solution";
     
    12201257                case CalvingHabEnum : return "CalvingHab";
    12211258                case CalvingLevermannEnum : return "CalvingLevermann";
     1259                case CalvingTestEnum : return "CalvingTest";
     1260                case CalvingParameterizationEnum : return "CalvingParameterization";
    12221261                case CalvingVonmisesEnum : return "CalvingVonmises";
    12231262                case CfdragcoeffabsgradEnum : return "Cfdragcoeffabsgrad";
     
    13481387                case JEnum : return "J";
    13491388                case L1L2ApproximationEnum : return "L1L2Approximation";
    1350                 case MLHOApproximationEnum : return "MLHOApproximation";
     1389                case MOLHOApproximationEnum : return "MOLHOApproximation";
    13511390                case L2ProjectionBaseAnalysisEnum : return "L2ProjectionBaseAnalysis";
    13521391                case L2ProjectionEPLAnalysisEnum : return "L2ProjectionEPLAnalysis";
     
    13601399                case LoadsEnum : return "Loads";
    13611400                case LoveAnalysisEnum : return "LoveAnalysis";
    1362                 case LoveHiEnum : return "LoveHi";
    1363                 case LoveHrEnum : return "LoveHr";
     1401                case LoveHfEnum : return "LoveHf";
     1402                case LoveHtEnum : return "LoveHt";
    13641403                case LoveKernelsImagEnum : return "LoveKernelsImag";
    13651404                case LoveKernelsRealEnum : return "LoveKernelsReal";
    1366                 case LoveKiEnum : return "LoveKi";
    1367                 case LoveKrEnum : return "LoveKr";
    1368                 case LoveLiEnum : return "LoveLi";
    1369                 case LoveLrEnum : return "LoveLr";
     1405                case LoveKfEnum : return "LoveKf";
     1406                case LoveKtEnum : return "LoveKt";
     1407                case LoveLfEnum : return "LoveLf";
     1408                case LoveLtEnum : return "LoveLt";
     1409                case LoveTidalHtEnum : return "LoveTidalHt";
     1410                case LoveTidalKtEnum : return "LoveTidalKt";
     1411                case LoveTidalLtEnum : return "LoveTidalLt";
     1412                case LovePMTF1tEnum : return "LovePMTF1t";
     1413                case LovePMTF2tEnum : return "LovePMTF2t";
    13701414                case LoveSolutionEnum : return "LoveSolution";
    13711415                case MINIEnum : return "MINI";
     
    14791523                case SealevelAbsoluteEnum : return "SealevelAbsolute";
    14801524                case SealevelEmotionEnum : return "SealevelEmotion";
    1481                 case SealevelInertiaTensorXZEnum : return "SealevelInertiaTensorXZ";
    1482                 case SealevelInertiaTensorYZEnum : return "SealevelInertiaTensorYZ";
    1483                 case SealevelInertiaTensorZZEnum : return "SealevelInertiaTensorZZ";
     1525                case SealevelchangePolarMotionXEnum : return "SealevelchangePolarMotionX";
     1526                case SealevelchangePolarMotionYEnum : return "SealevelchangePolarMotionY";
     1527                case SealevelchangePolarMotionZEnum : return "SealevelchangePolarMotionZ";
    14841528                case SealevelchangePolarMotionEnum : return "SealevelchangePolarMotion";
    14851529                case SealevelNmotionEnum : return "SealevelNmotion";
  • issm/trunk/src/c/shared/Enum/Enumjl.vim

    r26744 r27035  
    5757syn keyword juliaConstC BalancethicknessStabilizationEnum
    5858syn keyword juliaConstC BarystaticContributionsEnum
     59syn keyword juliaConstC BasalforcingsAutoregressionInitialTimeEnum
     60syn keyword juliaConstC BasalforcingsAutoregressionTimestepEnum
     61syn keyword juliaConstC BasalforcingsAutoregressiveOrderEnum
     62syn keyword juliaConstC BasalforcingsBeta0Enum
     63syn keyword juliaConstC BasalforcingsBeta1Enum
    5964syn keyword juliaConstC BasalforcingsBottomplumedepthEnum
    6065syn keyword juliaConstC BasalforcingsCrustthicknessEnum
     
    7075syn keyword juliaConstC BasalforcingsIsmip6NumBasinsEnum
    7176syn keyword juliaConstC BasalforcingsIsmip6TfDepthsEnum
     77syn keyword juliaConstC BasalforcingsLinearNumBasinsEnum
    7278syn keyword juliaConstC BasalforcingsLowercrustheatEnum
    7379syn keyword juliaConstC BasalforcingsMantleconductivityEnum
    7480syn keyword juliaConstC BasalforcingsNusseltEnum
     81syn keyword juliaConstC BasalforcingsPhiEnum
    7582syn keyword juliaConstC BasalforcingsPicoAverageOverturningEnum
    7683syn keyword juliaConstC BasalforcingsPicoAverageSalinityEnum
     
    98105syn keyword juliaConstC CalvingLawEnum
    99106syn keyword juliaConstC CalvingMinthicknessEnum
     107syn keyword juliaConstC CalvingTestSpeedfactorEnum
     108syn keyword juliaConstC CalvingTestIndependentRateEnum
     109syn keyword juliaConstC CalvingUseParamEnum
     110syn keyword juliaConstC CalvingScaleThetaEnum
     111syn keyword juliaConstC CalvingAmpAlphaEnum
     112syn keyword juliaConstC CalvingMidpointEnum
     113syn keyword juliaConstC CalvingNonlinearLawEnum
    100114syn keyword juliaConstC ConfigurationTypeEnum
    101115syn keyword juliaConstC ConstantsGEnum
     
    155169syn keyword juliaConstC FlowequationIsHOEnum
    156170syn keyword juliaConstC FlowequationIsL1L2Enum
    157 syn keyword juliaConstC FlowequationIsMLHOEnum
     171syn keyword juliaConstC FlowequationIsMOLHOEnum
    158172syn keyword juliaConstC FlowequationIsSIAEnum
    159173syn keyword juliaConstC FlowequationIsSSAEnum
     
    182196syn keyword juliaConstC GroundinglineMeltInterpolationEnum
    183197syn keyword juliaConstC GroundinglineMigrationEnum
     198syn keyword juliaConstC GroundinglineNumRequestedOutputsEnum
     199syn keyword juliaConstC GroundinglineRequestedOutputsEnum
    184200syn keyword juliaConstC HydrologyAveragingEnum
    185201syn keyword juliaConstC HydrologyCavitySpacingEnum
     
    256272syn keyword juliaConstC LockFileNameEnum
    257273syn keyword juliaConstC LoveAllowLayerDeletionEnum
     274syn keyword juliaConstC LoveChandlerWobbleEnum
    258275syn keyword juliaConstC LoveCoreMantleBoundaryEnum
    259276syn keyword juliaConstC LoveEarthMassEnum
     
    276293syn keyword juliaConstC LoveStartingLayerEnum
    277294syn keyword juliaConstC LoveUnderflowTolEnum
     295syn keyword juliaConstC LovePostWidderThresholdEnum
    278296syn keyword juliaConstC MassFluxSegmentsEnum
    279297syn keyword juliaConstC MassFluxSegmentsPresentEnum
     
    345363syn keyword juliaConstC ModelnameEnum
    346364syn keyword juliaConstC SamplingAlphaEnum
    347 syn keyword juliaConstC SamplingPhiEnum
    348365syn keyword juliaConstC SamplingNumRequestedOutputsEnum
    349366syn keyword juliaConstC SamplingRequestedOutputsEnum
    350367syn keyword juliaConstC SamplingRobinEnum
    351368syn keyword juliaConstC SamplingSeedEnum
    352 syn keyword juliaConstC SamplingTauEnum
    353369syn keyword juliaConstC SaveResultsEnum
    354370syn keyword juliaConstC SolidearthPartitionIceEnum
     
    362378syn keyword juliaConstC SolidearthSettingsAbstolEnum
    363379syn keyword juliaConstC SolidearthSettingsCrossSectionShapeEnum
    364 syn keyword juliaConstC RotationalAngularVelocityEnum
    365380syn keyword juliaConstC SolidearthSettingsElasticEnum
    366381syn keyword juliaConstC SolidearthSettingsViscousEnum
     
    369384syn keyword juliaConstC SealevelchangeViscousTimesEnum
    370385syn keyword juliaConstC SealevelchangeViscousIndexEnum
     386syn keyword juliaConstC SealevelchangeViscousPolarMotionEnum
     387syn keyword juliaConstC SealevelchangeRunCountEnum
     388syn keyword juliaConstC SealevelchangeTransitionsEnum
     389syn keyword juliaConstC SealevelchangeRequestedOutputsEnum
     390syn keyword juliaConstC RotationalAngularVelocityEnum
    371391syn keyword juliaConstC RotationalEquatorialMoiEnum
     392syn keyword juliaConstC RotationalPolarMoiEnum
     393syn keyword juliaConstC LovePolarMotionTransferFunctionColinearEnum
     394syn keyword juliaConstC LovePolarMotionTransferFunctionOrthogonalEnum
    372395syn keyword juliaConstC TidalLoveHEnum
    373396syn keyword juliaConstC TidalLoveKEnum
     
    381404syn keyword juliaConstC SealevelchangeGSelfAttractionEnum
    382405syn keyword juliaConstC SealevelchangeGViscoElasticEnum
     406syn keyword juliaConstC SealevelchangeUViscoElasticEnum
     407syn keyword juliaConstC SealevelchangeHViscoElasticEnum
     408syn keyword juliaConstC SealevelchangePolarMotionTransferFunctionColinearEnum
     409syn keyword juliaConstC SealevelchangePolarMotionTransferFunctionOrthogonalEnum
     410syn keyword juliaConstC SealevelchangePolarMotionTransferFunctionZEnum
     411syn keyword juliaConstC SealevelchangeTidalK2Enum
     412syn keyword juliaConstC SealevelchangeTidalH2Enum
     413syn keyword juliaConstC SealevelchangeTidalL2Enum
    383414syn keyword juliaConstC SolidearthSettingsSealevelLoadingEnum
    384415syn keyword juliaConstC SolidearthSettingsGRDEnum
    385416syn keyword juliaConstC SolidearthSettingsRunFrequencyEnum
    386417syn keyword juliaConstC SolidearthSettingsTimeAccEnum
    387 syn keyword juliaConstC SealevelchangeHViscoElasticEnum
    388418syn keyword juliaConstC SolidearthSettingsHorizEnum
    389419syn keyword juliaConstC SolidearthSettingsMaxiterEnum
     
    397427syn keyword juliaConstC StochasticForcingIsStochasticForcingEnum
    398428syn keyword juliaConstC StochasticForcingIsWaterPressureEnum
     429syn keyword juliaConstC StochasticForcingNoisetermsEnum
    399430syn keyword juliaConstC StochasticForcingNumFieldsEnum
    400431syn keyword juliaConstC StochasticForcingRandomflagEnum
    401 syn keyword juliaConstC RotationalPolarMoiEnum
     432syn keyword juliaConstC StochasticForcingTimestepEnum
    402433syn keyword juliaConstC SolidearthSettingsReltolEnum
    403 syn keyword juliaConstC SealevelchangeRequestedOutputsEnum
    404434syn keyword juliaConstC SolidearthSettingsSelfAttractionEnum
    405435syn keyword juliaConstC SolidearthSettingsRotationEnum
    406436syn keyword juliaConstC SolidearthSettingsMaxSHCoeffEnum
    407 syn keyword juliaConstC SealevelchangeRunCountEnum
    408 syn keyword juliaConstC SealevelchangeTransitionsEnum
    409 syn keyword juliaConstC SealevelchangeUViscoElasticEnum
    410437syn keyword juliaConstC SettingsIoGatherEnum
    411438syn keyword juliaConstC SettingsNumResultsOnNodesEnum
     
    432459syn keyword juliaConstC SmbDpermilEnum
    433460syn keyword juliaConstC SmbDsnowIdxEnum
     461syn keyword juliaConstC SmbElevationBinsEnum
    434462syn keyword juliaConstC SmbCldFracEnum
    435463syn keyword juliaConstC SmbDelta18oEnum
     
    459487syn keyword juliaConstC SmbIsturbulentfluxEnum
    460488syn keyword juliaConstC SmbKEnum
     489syn keyword juliaConstC SmbLapseRatesEnum
    461490syn keyword juliaConstC SmbNumBasinsEnum
     491syn keyword juliaConstC SmbNumElevationBinsEnum
    462492syn keyword juliaConstC SmbNumRequestedOutputsEnum
    463493syn keyword juliaConstC SmbPfacEnum
    464494syn keyword juliaConstC SmbPhiEnum
    465495syn keyword juliaConstC SmbRdlEnum
     496syn keyword juliaConstC SmbRefElevationEnum
    466497syn keyword juliaConstC SmbRequestedOutputsEnum
    467498syn keyword juliaConstC SmbRlapsEnum
     
    572603syn keyword juliaConstC BalancethicknessThickeningRateEnum
    573604syn keyword juliaConstC BasalCrevasseEnum
     605syn keyword juliaConstC BasalforcingsDeepwaterMeltingRateAutoregressionEnum
     606syn keyword juliaConstC BasalforcingsDeepwaterMeltingRateNoiseEnum
     607syn keyword juliaConstC BasalforcingsDeepwaterMeltingRateValuesAutoregressionEnum
    574608syn keyword juliaConstC BasalforcingsFloatingiceMeltingRateEnum
    575609syn keyword juliaConstC BasalforcingsGeothermalfluxEnum
    576610syn keyword juliaConstC BasalforcingsGroundediceMeltingRateEnum
     611syn keyword juliaConstC BasalforcingsLinearBasinIdEnum
    577612syn keyword juliaConstC BasalforcingsPerturbationMeltingRateEnum
     613syn keyword juliaConstC BasalforcingsSpatialDeepwaterElevationEnum
     614syn keyword juliaConstC BasalforcingsSpatialDeepwaterMeltingRateEnum
     615syn keyword juliaConstC BasalforcingsSpatialUpperwaterElevationEnum
     616syn keyword juliaConstC BasalforcingsSpatialUpperwaterMeltingRateEnum
    578617syn keyword juliaConstC BasalforcingsIsmip6BasinIdEnum
    579618syn keyword juliaConstC BasalforcingsIsmip6TfEnum
     
    597636syn keyword juliaConstC BaseSlopeYEnum
    598637syn keyword juliaConstC BaselineBasalforcingsFloatingiceMeltingRateEnum
     638syn keyword juliaConstC BaselineBasalforcingsSpatialDeepwaterMeltingRateEnum
    599639syn keyword juliaConstC BaselineCalvingCalvingrateEnum
    600640syn keyword juliaConstC BaselineFrictionEffectivePressureEnum
     641syn keyword juliaConstC BaselineSmbMassBalanceEnum
    601642syn keyword juliaConstC BedEnum
    602643syn keyword juliaConstC BedGRDEnum
     
    611652syn keyword juliaConstC CalvingCalvingrateEnum
    612653syn keyword juliaConstC CalvingHabFractionEnum
     654syn keyword juliaConstC CalvingAblationrateEnum
    613655syn keyword juliaConstC CalvingMeltingrateEnum
    614656syn keyword juliaConstC CalvingStressThresholdFloatingiceEnum
    615657syn keyword juliaConstC CalvingStressThresholdGroundediceEnum
    616658syn keyword juliaConstC CalvinglevermannCoeffEnum
    617 syn keyword juliaConstC CalvingratexAverageEnum
    618659syn keyword juliaConstC CalvingratexEnum
    619 syn keyword juliaConstC CalvingrateyAverageEnum
    620660syn keyword juliaConstC CalvingrateyEnum
    621661syn keyword juliaConstC CalvingFluxLevelsetEnum
     
    796836syn keyword juliaConstC RheologyBbarAbsGradientEnum
    797837syn keyword juliaConstC SampleEnum
     838syn keyword juliaConstC SampleOldEnum
     839syn keyword juliaConstC SampleNoiseEnum
    798840syn keyword juliaConstC SamplingBetaEnum
    799841syn keyword juliaConstC SamplingKappaEnum
     842syn keyword juliaConstC SamplingPhiEnum
     843syn keyword juliaConstC SamplingTauEnum
    800844syn keyword juliaConstC SealevelEnum
    801845syn keyword juliaConstC SealevelGRDEnum
     
    832876syn keyword juliaConstC BslcRateEnum
    833877syn keyword juliaConstC GmtslcEnum
    834 syn keyword juliaConstC SealevelGrotm1Enum
    835 syn keyword juliaConstC SealevelGrotm2Enum
    836 syn keyword juliaConstC SealevelGrotm3Enum
    837 syn keyword juliaConstC SealevelGUrotm1Enum
    838 syn keyword juliaConstC SealevelGUrotm2Enum
    839 syn keyword juliaConstC SealevelGUrotm3Enum
    840 syn keyword juliaConstC SealevelGNrotm1Enum
    841 syn keyword juliaConstC SealevelGNrotm2Enum
    842 syn keyword juliaConstC SealevelGNrotm3Enum
    843 syn keyword juliaConstC SealevelGErotm1Enum
    844 syn keyword juliaConstC SealevelGErotm2Enum
    845 syn keyword juliaConstC SealevelGErotm3Enum
    846878syn keyword juliaConstC SealevelRSLBarystaticEnum
    847879syn keyword juliaConstC SealevelRSLRateEnum
     
    855887syn keyword juliaConstC SealevelchangeGEEnum
    856888syn keyword juliaConstC SealevelchangeGNEnum
     889syn keyword juliaConstC SealevelchangeGrotEnum
     890syn keyword juliaConstC SealevelchangeGUrotEnum
     891syn keyword juliaConstC SealevelchangeGNrotEnum
     892syn keyword juliaConstC SealevelchangeGErotEnum
    857893syn keyword juliaConstC SealevelchangeGsubelOceanEnum
    858894syn keyword juliaConstC SealevelchangeGUsubelOceanEnum
     
    11881224syn keyword juliaConstC ArrheniusEnum
    11891225syn keyword juliaConstC AutodiffJacobianEnum
     1226syn keyword juliaConstC AutoregressionLinearFloatingMeltRateEnum
    11901227syn keyword juliaConstC Balancethickness2AnalysisEnum
    11911228syn keyword juliaConstC Balancethickness2SolutionEnum
     
    12111248syn keyword juliaConstC CalvingHabEnum
    12121249syn keyword juliaConstC CalvingLevermannEnum
     1250syn keyword juliaConstC CalvingTestEnum
     1251syn keyword juliaConstC CalvingParameterizationEnum
    12131252syn keyword juliaConstC CalvingVonmisesEnum
    12141253syn keyword juliaConstC CfdragcoeffabsgradEnum
     
    13391378syn keyword juliaConstC JEnum
    13401379syn keyword juliaConstC L1L2ApproximationEnum
    1341 syn keyword juliaConstC MLHOApproximationEnum
     1380syn keyword juliaConstC MOLHOApproximationEnum
    13421381syn keyword juliaConstC L2ProjectionBaseAnalysisEnum
    13431382syn keyword juliaConstC L2ProjectionEPLAnalysisEnum
     
    13511390syn keyword juliaConstC LoadsEnum
    13521391syn keyword juliaConstC LoveAnalysisEnum
    1353 syn keyword juliaConstC LoveHiEnum
    1354 syn keyword juliaConstC LoveHrEnum
     1392syn keyword juliaConstC LoveHfEnum
     1393syn keyword juliaConstC LoveHtEnum
    13551394syn keyword juliaConstC LoveKernelsImagEnum
    13561395syn keyword juliaConstC LoveKernelsRealEnum
    1357 syn keyword juliaConstC LoveKiEnum
    1358 syn keyword juliaConstC LoveKrEnum
    1359 syn keyword juliaConstC LoveLiEnum
    1360 syn keyword juliaConstC LoveLrEnum
     1396syn keyword juliaConstC LoveKfEnum
     1397syn keyword juliaConstC LoveKtEnum
     1398syn keyword juliaConstC LoveLfEnum
     1399syn keyword juliaConstC LoveLtEnum
     1400syn keyword juliaConstC LoveTidalHtEnum
     1401syn keyword juliaConstC LoveTidalKtEnum
     1402syn keyword juliaConstC LoveTidalLtEnum
     1403syn keyword juliaConstC LovePMTF1tEnum
     1404syn keyword juliaConstC LovePMTF2tEnum
    13611405syn keyword juliaConstC LoveSolutionEnum
    13621406syn keyword juliaConstC MINIEnum
     
    14701514syn keyword juliaConstC SealevelAbsoluteEnum
    14711515syn keyword juliaConstC SealevelEmotionEnum
    1472 syn keyword juliaConstC SealevelInertiaTensorXZEnum
    1473 syn keyword juliaConstC SealevelInertiaTensorYZEnum
    1474 syn keyword juliaConstC SealevelInertiaTensorZZEnum
     1516syn keyword juliaConstC SealevelchangePolarMotionXEnum
     1517syn keyword juliaConstC SealevelchangePolarMotionYEnum
     1518syn keyword juliaConstC SealevelchangePolarMotionZEnum
    14751519syn keyword juliaConstC SealevelchangePolarMotionEnum
    14761520syn keyword juliaConstC SealevelNmotionEnum
  • issm/trunk/src/c/shared/Enum/StringToEnumx.cpp

    r26744 r27035  
    6666              else if (strcmp(name,"BalancethicknessStabilization")==0) return BalancethicknessStabilizationEnum;
    6767              else if (strcmp(name,"BarystaticContributions")==0) return BarystaticContributionsEnum;
     68              else if (strcmp(name,"BasalforcingsAutoregressionInitialTime")==0) return BasalforcingsAutoregressionInitialTimeEnum;
     69              else if (strcmp(name,"BasalforcingsAutoregressionTimestep")==0) return BasalforcingsAutoregressionTimestepEnum;
     70              else if (strcmp(name,"BasalforcingsAutoregressiveOrder")==0) return BasalforcingsAutoregressiveOrderEnum;
     71              else if (strcmp(name,"BasalforcingsBeta0")==0) return BasalforcingsBeta0Enum;
     72              else if (strcmp(name,"BasalforcingsBeta1")==0) return BasalforcingsBeta1Enum;
    6873              else if (strcmp(name,"BasalforcingsBottomplumedepth")==0) return BasalforcingsBottomplumedepthEnum;
    6974              else if (strcmp(name,"BasalforcingsCrustthickness")==0) return BasalforcingsCrustthicknessEnum;
     
    7984              else if (strcmp(name,"BasalforcingsIsmip6NumBasins")==0) return BasalforcingsIsmip6NumBasinsEnum;
    8085              else if (strcmp(name,"BasalforcingsIsmip6TfDepths")==0) return BasalforcingsIsmip6TfDepthsEnum;
     86              else if (strcmp(name,"BasalforcingsLinearNumBasins")==0) return BasalforcingsLinearNumBasinsEnum;
    8187              else if (strcmp(name,"BasalforcingsLowercrustheat")==0) return BasalforcingsLowercrustheatEnum;
    8288              else if (strcmp(name,"BasalforcingsMantleconductivity")==0) return BasalforcingsMantleconductivityEnum;
    8389              else if (strcmp(name,"BasalforcingsNusselt")==0) return BasalforcingsNusseltEnum;
     90              else if (strcmp(name,"BasalforcingsPhi")==0) return BasalforcingsPhiEnum;
    8491              else if (strcmp(name,"BasalforcingsPicoAverageOverturning")==0) return BasalforcingsPicoAverageOverturningEnum;
    8592              else if (strcmp(name,"BasalforcingsPicoAverageSalinity")==0) return BasalforcingsPicoAverageSalinityEnum;
     
    107114              else if (strcmp(name,"CalvingLaw")==0) return CalvingLawEnum;
    108115              else if (strcmp(name,"CalvingMinthickness")==0) return CalvingMinthicknessEnum;
     116              else if (strcmp(name,"CalvingTestSpeedfactor")==0) return CalvingTestSpeedfactorEnum;
     117              else if (strcmp(name,"CalvingTestIndependentRate")==0) return CalvingTestIndependentRateEnum;
     118              else if (strcmp(name,"CalvingUseParam")==0) return CalvingUseParamEnum;
     119              else if (strcmp(name,"CalvingScaleTheta")==0) return CalvingScaleThetaEnum;
     120              else if (strcmp(name,"CalvingAmpAlpha")==0) return CalvingAmpAlphaEnum;
     121              else if (strcmp(name,"CalvingMidpoint")==0) return CalvingMidpointEnum;
     122              else if (strcmp(name,"CalvingNonlinearLaw")==0) return CalvingNonlinearLawEnum;
    109123              else if (strcmp(name,"ConfigurationType")==0) return ConfigurationTypeEnum;
    110124              else if (strcmp(name,"ConstantsG")==0) return ConstantsGEnum;
     
    123137              else if (strcmp(name,"CumBslcOceanPartition")==0) return CumBslcOceanPartitionEnum;
    124138              else if (strcmp(name,"CumGmtslc")==0) return CumGmtslcEnum;
    125               else if (strcmp(name,"CumGmslc")==0) return CumGmslcEnum;
     139         else stage=2;
     140   }
     141   if(stage==2){
     142              if (strcmp(name,"CumGmslc")==0) return CumGmslcEnum;
    126143              else if (strcmp(name,"DamageC1")==0) return DamageC1Enum;
    127144              else if (strcmp(name,"DamageC2")==0) return DamageC2Enum;
     
    137154              else if (strcmp(name,"DamageMaxDamage")==0) return DamageMaxDamageEnum;
    138155              else if (strcmp(name,"DamageStabilization")==0) return DamageStabilizationEnum;
    139          else stage=2;
    140    }
    141    if(stage==2){
    142               if (strcmp(name,"DamageStressThreshold")==0) return DamageStressThresholdEnum;
     156              else if (strcmp(name,"DamageStressThreshold")==0) return DamageStressThresholdEnum;
    143157              else if (strcmp(name,"DamageStressUBound")==0) return DamageStressUBoundEnum;
    144158              else if (strcmp(name,"DebugProfiling")==0) return DebugProfilingEnum;
     
    167181              else if (strcmp(name,"FlowequationIsHO")==0) return FlowequationIsHOEnum;
    168182              else if (strcmp(name,"FlowequationIsL1L2")==0) return FlowequationIsL1L2Enum;
    169               else if (strcmp(name,"FlowequationIsMLHO")==0) return FlowequationIsMLHOEnum;
     183              else if (strcmp(name,"FlowequationIsMOLHO")==0) return FlowequationIsMOLHOEnum;
    170184              else if (strcmp(name,"FlowequationIsSIA")==0) return FlowequationIsSIAEnum;
    171185              else if (strcmp(name,"FlowequationIsSSA")==0) return FlowequationIsSSAEnum;
     
    194208              else if (strcmp(name,"GroundinglineMeltInterpolation")==0) return GroundinglineMeltInterpolationEnum;
    195209              else if (strcmp(name,"GroundinglineMigration")==0) return GroundinglineMigrationEnum;
     210              else if (strcmp(name,"GroundinglineNumRequestedOutputs")==0) return GroundinglineNumRequestedOutputsEnum;
     211              else if (strcmp(name,"GroundinglineRequestedOutputs")==0) return GroundinglineRequestedOutputsEnum;
    196212              else if (strcmp(name,"HydrologyAveraging")==0) return HydrologyAveragingEnum;
    197213              else if (strcmp(name,"HydrologyCavitySpacing")==0) return HydrologyCavitySpacingEnum;
     
    244260              else if (strcmp(name,"InversionAlgorithm")==0) return InversionAlgorithmEnum;
    245261              else if (strcmp(name,"InversionControlParameters")==0) return InversionControlParametersEnum;
    246               else if (strcmp(name,"InversionControlScalingFactors")==0) return InversionControlScalingFactorsEnum;
     262         else stage=3;
     263   }
     264   if(stage==3){
     265              if (strcmp(name,"InversionControlScalingFactors")==0) return InversionControlScalingFactorsEnum;
    247266              else if (strcmp(name,"InversionCostFunctions")==0) return InversionCostFunctionsEnum;
    248267              else if (strcmp(name,"InversionDxmin")==0) return InversionDxminEnum;
     
    260279              else if (strcmp(name,"InversionNumCostFunctions")==0) return InversionNumCostFunctionsEnum;
    261280              else if (strcmp(name,"InversionStepThreshold")==0) return InversionStepThresholdEnum;
    262          else stage=3;
    263    }
    264    if(stage==3){
    265               if (strcmp(name,"InversionType")==0) return InversionTypeEnum;
     281              else if (strcmp(name,"InversionType")==0) return InversionTypeEnum;
    266282              else if (strcmp(name,"Ivins")==0) return IvinsEnum;
    267283              else if (strcmp(name,"IsSlcCoupling")==0) return IsSlcCouplingEnum;
     
    271287              else if (strcmp(name,"LockFileName")==0) return LockFileNameEnum;
    272288              else if (strcmp(name,"LoveAllowLayerDeletion")==0) return LoveAllowLayerDeletionEnum;
     289              else if (strcmp(name,"LoveChandlerWobble")==0) return LoveChandlerWobbleEnum;
    273290              else if (strcmp(name,"LoveCoreMantleBoundary")==0) return LoveCoreMantleBoundaryEnum;
    274291              else if (strcmp(name,"LoveEarthMass")==0) return LoveEarthMassEnum;
     
    291308              else if (strcmp(name,"LoveStartingLayer")==0) return LoveStartingLayerEnum;
    292309              else if (strcmp(name,"LoveUnderflowTol")==0) return LoveUnderflowTolEnum;
     310              else if (strcmp(name,"LovePostWidderThreshold")==0) return LovePostWidderThresholdEnum;
    293311              else if (strcmp(name,"MassFluxSegments")==0) return MassFluxSegmentsEnum;
    294312              else if (strcmp(name,"MassFluxSegmentsPresent")==0) return MassFluxSegmentsPresentEnum;
     
    360378              else if (strcmp(name,"Modelname")==0) return ModelnameEnum;
    361379              else if (strcmp(name,"SamplingAlpha")==0) return SamplingAlphaEnum;
    362               else if (strcmp(name,"SamplingPhi")==0) return SamplingPhiEnum;
    363380              else if (strcmp(name,"SamplingNumRequestedOutputs")==0) return SamplingNumRequestedOutputsEnum;
    364381              else if (strcmp(name,"SamplingRequestedOutputs")==0) return SamplingRequestedOutputsEnum;
    365382              else if (strcmp(name,"SamplingRobin")==0) return SamplingRobinEnum;
    366383              else if (strcmp(name,"SamplingSeed")==0) return SamplingSeedEnum;
    367               else if (strcmp(name,"SamplingTau")==0) return SamplingTauEnum;
    368384              else if (strcmp(name,"SaveResults")==0) return SaveResultsEnum;
    369               else if (strcmp(name,"SolidearthPartitionIce")==0) return SolidearthPartitionIceEnum;
     385         else stage=4;
     386   }
     387   if(stage==4){
     388              if (strcmp(name,"SolidearthPartitionIce")==0) return SolidearthPartitionIceEnum;
    370389              else if (strcmp(name,"SolidearthPartitionHydro")==0) return SolidearthPartitionHydroEnum;
    371390              else if (strcmp(name,"SolidearthPartitionOcean")==0) return SolidearthPartitionOceanEnum;
     
    377396              else if (strcmp(name,"SolidearthSettingsAbstol")==0) return SolidearthSettingsAbstolEnum;
    378397              else if (strcmp(name,"SolidearthSettingsCrossSectionShape")==0) return SolidearthSettingsCrossSectionShapeEnum;
    379               else if (strcmp(name,"RotationalAngularVelocity")==0) return RotationalAngularVelocityEnum;
    380398              else if (strcmp(name,"SolidearthSettingsElastic")==0) return SolidearthSettingsElasticEnum;
    381399              else if (strcmp(name,"SolidearthSettingsViscous")==0) return SolidearthSettingsViscousEnum;
     
    383401              else if (strcmp(name,"SealevelchangeViscousNumSteps")==0) return SealevelchangeViscousNumStepsEnum;
    384402              else if (strcmp(name,"SealevelchangeViscousTimes")==0) return SealevelchangeViscousTimesEnum;
    385          else stage=4;
    386    }
    387    if(stage==4){
    388               if (strcmp(name,"SealevelchangeViscousIndex")==0) return SealevelchangeViscousIndexEnum;
     403              else if (strcmp(name,"SealevelchangeViscousIndex")==0) return SealevelchangeViscousIndexEnum;
     404              else if (strcmp(name,"SealevelchangeViscousPolarMotion")==0) return SealevelchangeViscousPolarMotionEnum;
     405              else if (strcmp(name,"SealevelchangeRunCount")==0) return SealevelchangeRunCountEnum;
     406              else if (strcmp(name,"SealevelchangeTransitions")==0) return SealevelchangeTransitionsEnum;
     407              else if (strcmp(name,"SealevelchangeRequestedOutputs")==0) return SealevelchangeRequestedOutputsEnum;
     408              else if (strcmp(name,"RotationalAngularVelocity")==0) return RotationalAngularVelocityEnum;
    389409              else if (strcmp(name,"RotationalEquatorialMoi")==0) return RotationalEquatorialMoiEnum;
     410              else if (strcmp(name,"RotationalPolarMoi")==0) return RotationalPolarMoiEnum;
     411              else if (strcmp(name,"LovePolarMotionTransferFunctionColinear")==0) return LovePolarMotionTransferFunctionColinearEnum;
     412              else if (strcmp(name,"LovePolarMotionTransferFunctionOrthogonal")==0) return LovePolarMotionTransferFunctionOrthogonalEnum;
    390413              else if (strcmp(name,"TidalLoveH")==0) return TidalLoveHEnum;
    391414              else if (strcmp(name,"TidalLoveK")==0) return TidalLoveKEnum;
     
    399422              else if (strcmp(name,"SealevelchangeGSelfAttraction")==0) return SealevelchangeGSelfAttractionEnum;
    400423              else if (strcmp(name,"SealevelchangeGViscoElastic")==0) return SealevelchangeGViscoElasticEnum;
     424              else if (strcmp(name,"SealevelchangeUViscoElastic")==0) return SealevelchangeUViscoElasticEnum;
     425              else if (strcmp(name,"SealevelchangeHViscoElastic")==0) return SealevelchangeHViscoElasticEnum;
     426              else if (strcmp(name,"SealevelchangePolarMotionTransferFunctionColinear")==0) return SealevelchangePolarMotionTransferFunctionColinearEnum;
     427              else if (strcmp(name,"SealevelchangePolarMotionTransferFunctionOrthogonal")==0) return SealevelchangePolarMotionTransferFunctionOrthogonalEnum;
     428              else if (strcmp(name,"SealevelchangePolarMotionTransferFunctionZ")==0) return SealevelchangePolarMotionTransferFunctionZEnum;
     429              else if (strcmp(name,"SealevelchangeTidalK2")==0) return SealevelchangeTidalK2Enum;
     430              else if (strcmp(name,"SealevelchangeTidalH2")==0) return SealevelchangeTidalH2Enum;
     431              else if (strcmp(name,"SealevelchangeTidalL2")==0) return SealevelchangeTidalL2Enum;
    401432              else if (strcmp(name,"SolidearthSettingsSealevelLoading")==0) return SolidearthSettingsSealevelLoadingEnum;
    402433              else if (strcmp(name,"SolidearthSettingsGRD")==0) return SolidearthSettingsGRDEnum;
    403434              else if (strcmp(name,"SolidearthSettingsRunFrequency")==0) return SolidearthSettingsRunFrequencyEnum;
    404435              else if (strcmp(name,"SolidearthSettingsTimeAcc")==0) return SolidearthSettingsTimeAccEnum;
    405               else if (strcmp(name,"SealevelchangeHViscoElastic")==0) return SealevelchangeHViscoElasticEnum;
    406436              else if (strcmp(name,"SolidearthSettingsHoriz")==0) return SolidearthSettingsHorizEnum;
    407437              else if (strcmp(name,"SolidearthSettingsMaxiter")==0) return SolidearthSettingsMaxiterEnum;
     
    415445              else if (strcmp(name,"StochasticForcingIsStochasticForcing")==0) return StochasticForcingIsStochasticForcingEnum;
    416446              else if (strcmp(name,"StochasticForcingIsWaterPressure")==0) return StochasticForcingIsWaterPressureEnum;
     447              else if (strcmp(name,"StochasticForcingNoiseterms")==0) return StochasticForcingNoisetermsEnum;
    417448              else if (strcmp(name,"StochasticForcingNumFields")==0) return StochasticForcingNumFieldsEnum;
    418449              else if (strcmp(name,"StochasticForcingRandomflag")==0) return StochasticForcingRandomflagEnum;
    419               else if (strcmp(name,"RotationalPolarMoi")==0) return RotationalPolarMoiEnum;
     450              else if (strcmp(name,"StochasticForcingTimestep")==0) return StochasticForcingTimestepEnum;
    420451              else if (strcmp(name,"SolidearthSettingsReltol")==0) return SolidearthSettingsReltolEnum;
    421               else if (strcmp(name,"SealevelchangeRequestedOutputs")==0) return SealevelchangeRequestedOutputsEnum;
    422452              else if (strcmp(name,"SolidearthSettingsSelfAttraction")==0) return SolidearthSettingsSelfAttractionEnum;
    423453              else if (strcmp(name,"SolidearthSettingsRotation")==0) return SolidearthSettingsRotationEnum;
    424454              else if (strcmp(name,"SolidearthSettingsMaxSHCoeff")==0) return SolidearthSettingsMaxSHCoeffEnum;
    425               else if (strcmp(name,"SealevelchangeRunCount")==0) return SealevelchangeRunCountEnum;
    426               else if (strcmp(name,"SealevelchangeTransitions")==0) return SealevelchangeTransitionsEnum;
    427               else if (strcmp(name,"SealevelchangeUViscoElastic")==0) return SealevelchangeUViscoElasticEnum;
    428455              else if (strcmp(name,"SettingsIoGather")==0) return SettingsIoGatherEnum;
    429456              else if (strcmp(name,"SettingsNumResultsOnNodes")==0) return SettingsNumResultsOnNodesEnum;
     
    450477              else if (strcmp(name,"SmbDpermil")==0) return SmbDpermilEnum;
    451478              else if (strcmp(name,"SmbDsnowIdx")==0) return SmbDsnowIdxEnum;
     479              else if (strcmp(name,"SmbElevationBins")==0) return SmbElevationBinsEnum;
    452480              else if (strcmp(name,"SmbCldFrac")==0) return SmbCldFracEnum;
    453481              else if (strcmp(name,"SmbDelta18o")==0) return SmbDelta18oEnum;
     
    477505              else if (strcmp(name,"SmbIsturbulentflux")==0) return SmbIsturbulentfluxEnum;
    478506              else if (strcmp(name,"SmbK")==0) return SmbKEnum;
    479               else if (strcmp(name,"SmbNumBasins")==0) return SmbNumBasinsEnum;
     507              else if (strcmp(name,"SmbLapseRates")==0) return SmbLapseRatesEnum;
     508         else stage=5;
     509   }
     510   if(stage==5){
     511              if (strcmp(name,"SmbNumBasins")==0) return SmbNumBasinsEnum;
     512              else if (strcmp(name,"SmbNumElevationBins")==0) return SmbNumElevationBinsEnum;
    480513              else if (strcmp(name,"SmbNumRequestedOutputs")==0) return SmbNumRequestedOutputsEnum;
    481514              else if (strcmp(name,"SmbPfac")==0) return SmbPfacEnum;
    482515              else if (strcmp(name,"SmbPhi")==0) return SmbPhiEnum;
    483516              else if (strcmp(name,"SmbRdl")==0) return SmbRdlEnum;
     517              else if (strcmp(name,"SmbRefElevation")==0) return SmbRefElevationEnum;
    484518              else if (strcmp(name,"SmbRequestedOutputs")==0) return SmbRequestedOutputsEnum;
    485519              else if (strcmp(name,"SmbRlaps")==0) return SmbRlapsEnum;
     
    506540              else if (strcmp(name,"Step")==0) return StepEnum;
    507541              else if (strcmp(name,"Steps")==0) return StepsEnum;
    508          else stage=5;
    509    }
    510    if(stage==5){
    511               if (strcmp(name,"StressbalanceAbstol")==0) return StressbalanceAbstolEnum;
     542              else if (strcmp(name,"StressbalanceAbstol")==0) return StressbalanceAbstolEnum;
    512543              else if (strcmp(name,"StressbalanceFSreconditioning")==0) return StressbalanceFSreconditioningEnum;
    513544              else if (strcmp(name,"StressbalanceIsnewton")==0) return StressbalanceIsnewtonEnum;
     
    593624              else if (strcmp(name,"BalancethicknessThickeningRate")==0) return BalancethicknessThickeningRateEnum;
    594625              else if (strcmp(name,"BasalCrevasse")==0) return BasalCrevasseEnum;
     626              else if (strcmp(name,"BasalforcingsDeepwaterMeltingRateAutoregression")==0) return BasalforcingsDeepwaterMeltingRateAutoregressionEnum;
     627              else if (strcmp(name,"BasalforcingsDeepwaterMeltingRateNoise")==0) return BasalforcingsDeepwaterMeltingRateNoiseEnum;
     628              else if (strcmp(name,"BasalforcingsDeepwaterMeltingRateValuesAutoregression")==0) return BasalforcingsDeepwaterMeltingRateValuesAutoregressionEnum;
    595629              else if (strcmp(name,"BasalforcingsFloatingiceMeltingRate")==0) return BasalforcingsFloatingiceMeltingRateEnum;
    596630              else if (strcmp(name,"BasalforcingsGeothermalflux")==0) return BasalforcingsGeothermalfluxEnum;
    597               else if (strcmp(name,"BasalforcingsGroundediceMeltingRate")==0) return BasalforcingsGroundediceMeltingRateEnum;
     631         else stage=6;
     632   }
     633   if(stage==6){
     634              if (strcmp(name,"BasalforcingsGroundediceMeltingRate")==0) return BasalforcingsGroundediceMeltingRateEnum;
     635              else if (strcmp(name,"BasalforcingsLinearBasinId")==0) return BasalforcingsLinearBasinIdEnum;
    598636              else if (strcmp(name,"BasalforcingsPerturbationMeltingRate")==0) return BasalforcingsPerturbationMeltingRateEnum;
     637              else if (strcmp(name,"BasalforcingsSpatialDeepwaterElevation")==0) return BasalforcingsSpatialDeepwaterElevationEnum;
     638              else if (strcmp(name,"BasalforcingsSpatialDeepwaterMeltingRate")==0) return BasalforcingsSpatialDeepwaterMeltingRateEnum;
     639              else if (strcmp(name,"BasalforcingsSpatialUpperwaterElevation")==0) return BasalforcingsSpatialUpperwaterElevationEnum;
     640              else if (strcmp(name,"BasalforcingsSpatialUpperwaterMeltingRate")==0) return BasalforcingsSpatialUpperwaterMeltingRateEnum;
    599641              else if (strcmp(name,"BasalforcingsIsmip6BasinId")==0) return BasalforcingsIsmip6BasinIdEnum;
    600642              else if (strcmp(name,"BasalforcingsIsmip6Tf")==0) return BasalforcingsIsmip6TfEnum;
     
    618660              else if (strcmp(name,"BaseSlopeY")==0) return BaseSlopeYEnum;
    619661              else if (strcmp(name,"BaselineBasalforcingsFloatingiceMeltingRate")==0) return BaselineBasalforcingsFloatingiceMeltingRateEnum;
     662              else if (strcmp(name,"BaselineBasalforcingsSpatialDeepwaterMeltingRate")==0) return BaselineBasalforcingsSpatialDeepwaterMeltingRateEnum;
    620663              else if (strcmp(name,"BaselineCalvingCalvingrate")==0) return BaselineCalvingCalvingrateEnum;
    621664              else if (strcmp(name,"BaselineFrictionEffectivePressure")==0) return BaselineFrictionEffectivePressureEnum;
     665              else if (strcmp(name,"BaselineSmbMassBalance")==0) return BaselineSmbMassBalanceEnum;
    622666              else if (strcmp(name,"Bed")==0) return BedEnum;
    623667              else if (strcmp(name,"BedGRD")==0) return BedGRDEnum;
     
    629673              else if (strcmp(name,"BedSlopeY")==0) return BedSlopeYEnum;
    630674              else if (strcmp(name,"BottomPressure")==0) return BottomPressureEnum;
    631          else stage=6;
    632    }
    633    if(stage==6){
    634               if (strcmp(name,"BottomPressureOld")==0) return BottomPressureOldEnum;
     675              else if (strcmp(name,"BottomPressureOld")==0) return BottomPressureOldEnum;
    635676              else if (strcmp(name,"CalvingCalvingrate")==0) return CalvingCalvingrateEnum;
    636677              else if (strcmp(name,"CalvingHabFraction")==0) return CalvingHabFractionEnum;
     678              else if (strcmp(name,"CalvingAblationrate")==0) return CalvingAblationrateEnum;
    637679              else if (strcmp(name,"CalvingMeltingrate")==0) return CalvingMeltingrateEnum;
    638680              else if (strcmp(name,"CalvingStressThresholdFloatingice")==0) return CalvingStressThresholdFloatingiceEnum;
    639681              else if (strcmp(name,"CalvingStressThresholdGroundedice")==0) return CalvingStressThresholdGroundediceEnum;
    640682              else if (strcmp(name,"CalvinglevermannCoeff")==0) return CalvinglevermannCoeffEnum;
    641               else if (strcmp(name,"CalvingratexAverage")==0) return CalvingratexAverageEnum;
    642683              else if (strcmp(name,"Calvingratex")==0) return CalvingratexEnum;
    643               else if (strcmp(name,"CalvingrateyAverage")==0) return CalvingrateyAverageEnum;
    644684              else if (strcmp(name,"Calvingratey")==0) return CalvingrateyEnum;
    645685              else if (strcmp(name,"CalvingFluxLevelset")==0) return CalvingFluxLevelsetEnum;
     
    712752              else if (strcmp(name,"FrictionP")==0) return FrictionPEnum;
    713753              else if (strcmp(name,"FrictionPressureAdjustedTemperature")==0) return FrictionPressureAdjustedTemperatureEnum;
    714               else if (strcmp(name,"FrictionQ")==0) return FrictionQEnum;
     754         else stage=7;
     755   }
     756   if(stage==7){
     757              if (strcmp(name,"FrictionQ")==0) return FrictionQEnum;
    715758              else if (strcmp(name,"FrictionSedimentCompressibilityCoefficient")==0) return FrictionSedimentCompressibilityCoefficientEnum;
    716759              else if (strcmp(name,"FrictionTillFrictionAngle")==0) return FrictionTillFrictionAngleEnum;
     
    752795              else if (strcmp(name,"HydrologyHeadOld")==0) return HydrologyHeadOldEnum;
    753796              else if (strcmp(name,"HydrologyMoulinInput")==0) return HydrologyMoulinInputEnum;
    754          else stage=7;
    755    }
    756    if(stage==7){
    757               if (strcmp(name,"HydrologyNeumannflux")==0) return HydrologyNeumannfluxEnum;
     797              else if (strcmp(name,"HydrologyNeumannflux")==0) return HydrologyNeumannfluxEnum;
    758798              else if (strcmp(name,"HydrologyReynolds")==0) return HydrologyReynoldsEnum;
    759799              else if (strcmp(name,"HydrologySheetConductivity")==0) return HydrologySheetConductivityEnum;
     
    823863              else if (strcmp(name,"RheologyBbarAbsGradient")==0) return RheologyBbarAbsGradientEnum;
    824864              else if (strcmp(name,"Sample")==0) return SampleEnum;
     865              else if (strcmp(name,"SampleOld")==0) return SampleOldEnum;
     866              else if (strcmp(name,"SampleNoise")==0) return SampleNoiseEnum;
    825867              else if (strcmp(name,"SamplingBeta")==0) return SamplingBetaEnum;
    826868              else if (strcmp(name,"SamplingKappa")==0) return SamplingKappaEnum;
     869              else if (strcmp(name,"SamplingPhi")==0) return SamplingPhiEnum;
     870              else if (strcmp(name,"SamplingTau")==0) return SamplingTauEnum;
    827871              else if (strcmp(name,"Sealevel")==0) return SealevelEnum;
    828872              else if (strcmp(name,"SealevelGRD")==0) return SealevelGRDEnum;
     
    831875              else if (strcmp(name,"SealevelBarystaticIceWeights")==0) return SealevelBarystaticIceWeightsEnum;
    832876              else if (strcmp(name,"SealevelBarystaticIceArea")==0) return SealevelBarystaticIceAreaEnum;
    833               else if (strcmp(name,"SealevelBarystaticIceLatbar")==0) return SealevelBarystaticIceLatbarEnum;
     877         else stage=8;
     878   }
     879   if(stage==8){
     880              if (strcmp(name,"SealevelBarystaticIceLatbar")==0) return SealevelBarystaticIceLatbarEnum;
    834881              else if (strcmp(name,"SealevelBarystaticIceLongbar")==0) return SealevelBarystaticIceLongbarEnum;
    835882              else if (strcmp(name,"SealevelBarystaticIceLoad")==0) return SealevelBarystaticIceLoadEnum;
     
    859906              else if (strcmp(name,"BslcRate")==0) return BslcRateEnum;
    860907              else if (strcmp(name,"Gmtslc")==0) return GmtslcEnum;
    861               else if (strcmp(name,"SealevelGrotm1")==0) return SealevelGrotm1Enum;
    862               else if (strcmp(name,"SealevelGrotm2")==0) return SealevelGrotm2Enum;
    863               else if (strcmp(name,"SealevelGrotm3")==0) return SealevelGrotm3Enum;
    864               else if (strcmp(name,"SealevelGUrotm1")==0) return SealevelGUrotm1Enum;
    865               else if (strcmp(name,"SealevelGUrotm2")==0) return SealevelGUrotm2Enum;
    866               else if (strcmp(name,"SealevelGUrotm3")==0) return SealevelGUrotm3Enum;
    867               else if (strcmp(name,"SealevelGNrotm1")==0) return SealevelGNrotm1Enum;
    868               else if (strcmp(name,"SealevelGNrotm2")==0) return SealevelGNrotm2Enum;
    869               else if (strcmp(name,"SealevelGNrotm3")==0) return SealevelGNrotm3Enum;
    870               else if (strcmp(name,"SealevelGErotm1")==0) return SealevelGErotm1Enum;
    871               else if (strcmp(name,"SealevelGErotm2")==0) return SealevelGErotm2Enum;
    872               else if (strcmp(name,"SealevelGErotm3")==0) return SealevelGErotm3Enum;
    873908              else if (strcmp(name,"SealevelRSLBarystatic")==0) return SealevelRSLBarystaticEnum;
    874909              else if (strcmp(name,"SealevelRSLRate")==0) return SealevelRSLRateEnum;
    875910              else if (strcmp(name,"SealevelUGrd")==0) return SealevelUGrdEnum;
    876911              else if (strcmp(name,"SealevelNGrd")==0) return SealevelNGrdEnum;
    877          else stage=8;
    878    }
    879    if(stage==8){
    880               if (strcmp(name,"SealevelUEastEsa")==0) return SealevelUEastEsaEnum;
     912              else if (strcmp(name,"SealevelUEastEsa")==0) return SealevelUEastEsaEnum;
    881913              else if (strcmp(name,"SealevelUNorthEsa")==0) return SealevelUNorthEsaEnum;
    882914              else if (strcmp(name,"SealevelchangeIndices")==0) return SealevelchangeIndicesEnum;
     
    885917              else if (strcmp(name,"SealevelchangeGE")==0) return SealevelchangeGEEnum;
    886918              else if (strcmp(name,"SealevelchangeGN")==0) return SealevelchangeGNEnum;
     919              else if (strcmp(name,"SealevelchangeGrot")==0) return SealevelchangeGrotEnum;
     920              else if (strcmp(name,"SealevelchangeGUrot")==0) return SealevelchangeGUrotEnum;
     921              else if (strcmp(name,"SealevelchangeGNrot")==0) return SealevelchangeGNrotEnum;
     922              else if (strcmp(name,"SealevelchangeGErot")==0) return SealevelchangeGErotEnum;
    887923              else if (strcmp(name,"SealevelchangeGsubelOcean")==0) return SealevelchangeGsubelOceanEnum;
    888924              else if (strcmp(name,"SealevelchangeGUsubelOcean")==0) return SealevelchangeGUsubelOceanEnum;
     
    962998              else if (strcmp(name,"SmbGdnini")==0) return SmbGdniniEnum;
    963999              else if (strcmp(name,"SmbGsp")==0) return SmbGspEnum;
    964               else if (strcmp(name,"SmbGspini")==0) return SmbGspiniEnum;
     1000         else stage=9;
     1001   }
     1002   if(stage==9){
     1003              if (strcmp(name,"SmbGspini")==0) return SmbGspiniEnum;
    9651004              else if (strcmp(name,"SmbHref")==0) return SmbHrefEnum;
    9661005              else if (strcmp(name,"SmbIsInitialized")==0) return SmbIsInitializedEnum;
     
    9981037              else if (strcmp(name,"SmbSizeini")==0) return SmbSizeiniEnum;
    9991038              else if (strcmp(name,"SmbSmbCorr")==0) return SmbSmbCorrEnum;
    1000          else stage=9;
    1001    }
    1002    if(stage==9){
    1003               if (strcmp(name,"SmbSmbref")==0) return SmbSmbrefEnum;
     1039              else if (strcmp(name,"SmbSmbref")==0) return SmbSmbrefEnum;
    10041040              else if (strcmp(name,"SmbSzaValue")==0) return SmbSzaValueEnum;
    10051041              else if (strcmp(name,"SmbT")==0) return SmbTEnum;
     
    10851121              else if (strcmp(name,"VxSurface")==0) return VxSurfaceEnum;
    10861122              else if (strcmp(name,"VyAverage")==0) return VyAverageEnum;
    1087               else if (strcmp(name,"VyBase")==0) return VyBaseEnum;
     1123         else stage=10;
     1124   }
     1125   if(stage==10){
     1126              if (strcmp(name,"VyBase")==0) return VyBaseEnum;
    10881127              else if (strcmp(name,"Vy")==0) return VyEnum;
    10891128              else if (strcmp(name,"VyMesh")==0) return VyMeshEnum;
     
    11211160              else if (strcmp(name,"Outputdefinition19")==0) return Outputdefinition19Enum;
    11221161              else if (strcmp(name,"Outputdefinition20")==0) return Outputdefinition20Enum;
    1123          else stage=10;
    1124    }
    1125    if(stage==10){
    1126               if (strcmp(name,"Outputdefinition21")==0) return Outputdefinition21Enum;
     1162              else if (strcmp(name,"Outputdefinition21")==0) return Outputdefinition21Enum;
    11271163              else if (strcmp(name,"Outputdefinition22")==0) return Outputdefinition22Enum;
    11281164              else if (strcmp(name,"Outputdefinition23")==0) return Outputdefinition23Enum;
     
    12081244              else if (strcmp(name,"Outputdefinition96")==0) return Outputdefinition96Enum;
    12091245              else if (strcmp(name,"Outputdefinition97")==0) return Outputdefinition97Enum;
    1210               else if (strcmp(name,"Outputdefinition98")==0) return Outputdefinition98Enum;
     1246         else stage=11;
     1247   }
     1248   if(stage==11){
     1249              if (strcmp(name,"Outputdefinition98")==0) return Outputdefinition98Enum;
    12111250              else if (strcmp(name,"Outputdefinition99")==0) return Outputdefinition99Enum;
    12121251              else if (strcmp(name,"Outputdefinition9")==0) return Outputdefinition9Enum;
     
    12241263              else if (strcmp(name,"Arrhenius")==0) return ArrheniusEnum;
    12251264              else if (strcmp(name,"AutodiffJacobian")==0) return AutodiffJacobianEnum;
     1265              else if (strcmp(name,"AutoregressionLinearFloatingMeltRate")==0) return AutoregressionLinearFloatingMeltRateEnum;
    12261266              else if (strcmp(name,"Balancethickness2Analysis")==0) return Balancethickness2AnalysisEnum;
    12271267              else if (strcmp(name,"Balancethickness2Solution")==0) return Balancethickness2SolutionEnum;
     
    12441284              else if (strcmp(name,"Boundary")==0) return BoundaryEnum;
    12451285              else if (strcmp(name,"BuddJacka")==0) return BuddJackaEnum;
    1246          else stage=11;
    1247    }
    1248    if(stage==11){
    1249               if (strcmp(name,"CalvingDev2")==0) return CalvingDev2Enum;
     1286              else if (strcmp(name,"CalvingDev2")==0) return CalvingDev2Enum;
    12501287              else if (strcmp(name,"CalvingHab")==0) return CalvingHabEnum;
    12511288              else if (strcmp(name,"CalvingLevermann")==0) return CalvingLevermannEnum;
     1289              else if (strcmp(name,"CalvingTest")==0) return CalvingTestEnum;
     1290              else if (strcmp(name,"CalvingParameterization")==0) return CalvingParameterizationEnum;
    12521291              else if (strcmp(name,"CalvingVonmises")==0) return CalvingVonmisesEnum;
    12531292              else if (strcmp(name,"Cfdragcoeffabsgrad")==0) return CfdragcoeffabsgradEnum;
     
    13281367              else if (strcmp(name,"GaussTetra")==0) return GaussTetraEnum;
    13291368              else if (strcmp(name,"GaussTria")==0) return GaussTriaEnum;
    1330               else if (strcmp(name,"GenericOption")==0) return GenericOptionEnum;
     1369         else stage=12;
     1370   }
     1371   if(stage==12){
     1372              if (strcmp(name,"GenericOption")==0) return GenericOptionEnum;
    13311373              else if (strcmp(name,"GenericParam")==0) return GenericParamEnum;
    13321374              else if (strcmp(name,"GenericExternalResult")==0) return GenericExternalResultEnum;
     
    13671409              else if (strcmp(name,"Indexed")==0) return IndexedEnum;
    13681410              else if (strcmp(name,"IntExternalResult")==0) return IntExternalResultEnum;
    1369          else stage=12;
    1370    }
    1371    if(stage==12){
    1372               if (strcmp(name,"ElementInput")==0) return ElementInputEnum;
     1411              else if (strcmp(name,"ElementInput")==0) return ElementInputEnum;
    13731412              else if (strcmp(name,"IntMatExternalResult")==0) return IntMatExternalResultEnum;
    13741413              else if (strcmp(name,"IntMatParam")==0) return IntMatParamEnum;
     
    13811420              else if (strcmp(name,"J")==0) return JEnum;
    13821421              else if (strcmp(name,"L1L2Approximation")==0) return L1L2ApproximationEnum;
    1383               else if (strcmp(name,"MLHOApproximation")==0) return MLHOApproximationEnum;
     1422              else if (strcmp(name,"MOLHOApproximation")==0) return MOLHOApproximationEnum;
    13841423              else if (strcmp(name,"L2ProjectionBaseAnalysis")==0) return L2ProjectionBaseAnalysisEnum;
    13851424              else if (strcmp(name,"L2ProjectionEPLAnalysis")==0) return L2ProjectionEPLAnalysisEnum;
     
    13931432              else if (strcmp(name,"Loads")==0) return LoadsEnum;
    13941433              else if (strcmp(name,"LoveAnalysis")==0) return LoveAnalysisEnum;
    1395               else if (strcmp(name,"LoveHi")==0) return LoveHiEnum;
    1396               else if (strcmp(name,"LoveHr")==0) return LoveHrEnum;
     1434              else if (strcmp(name,"LoveHf")==0) return LoveHfEnum;
     1435              else if (strcmp(name,"LoveHt")==0) return LoveHtEnum;
    13971436              else if (strcmp(name,"LoveKernelsImag")==0) return LoveKernelsImagEnum;
    13981437              else if (strcmp(name,"LoveKernelsReal")==0) return LoveKernelsRealEnum;
    1399               else if (strcmp(name,"LoveKi")==0) return LoveKiEnum;
    1400               else if (strcmp(name,"LoveKr")==0) return LoveKrEnum;
    1401               else if (strcmp(name,"LoveLi")==0) return LoveLiEnum;
    1402               else if (strcmp(name,"LoveLr")==0) return LoveLrEnum;
     1438              else if (strcmp(name,"LoveKf")==0) return LoveKfEnum;
     1439              else if (strcmp(name,"LoveKt")==0) return LoveKtEnum;
     1440              else if (strcmp(name,"LoveLf")==0) return LoveLfEnum;
     1441              else if (strcmp(name,"LoveLt")==0) return LoveLtEnum;
     1442              else if (strcmp(name,"LoveTidalHt")==0) return LoveTidalHtEnum;
     1443              else if (strcmp(name,"LoveTidalKt")==0) return LoveTidalKtEnum;
     1444              else if (strcmp(name,"LoveTidalLt")==0) return LoveTidalLtEnum;
     1445              else if (strcmp(name,"LovePMTF1t")==0) return LovePMTF1tEnum;
     1446              else if (strcmp(name,"LovePMTF2t")==0) return LovePMTF2tEnum;
    14031447              else if (strcmp(name,"LoveSolution")==0) return LoveSolutionEnum;
    14041448              else if (strcmp(name,"MINI")==0) return MINIEnum;
     
    14461490              else if (strcmp(name,"Nodal")==0) return NodalEnum;
    14471491              else if (strcmp(name,"Nodalvalue")==0) return NodalvalueEnum;
    1448               else if (strcmp(name,"NodeSId")==0) return NodeSIdEnum;
     1492         else stage=13;
     1493   }
     1494   if(stage==13){
     1495              if (strcmp(name,"NodeSId")==0) return NodeSIdEnum;
    14491496              else if (strcmp(name,"NoneApproximation")==0) return NoneApproximationEnum;
    14501497              else if (strcmp(name,"None")==0) return NoneEnum;
     
    14901537              else if (strcmp(name,"Riftfront")==0) return RiftfrontEnum;
    14911538              else if (strcmp(name,"SamplingAnalysis")==0) return SamplingAnalysisEnum;
    1492          else stage=13;
    1493    }
    1494    if(stage==13){
    1495               if (strcmp(name,"SamplingSolution")==0) return SamplingSolutionEnum;
     1539              else if (strcmp(name,"SamplingSolution")==0) return SamplingSolutionEnum;
    14961540              else if (strcmp(name,"SIAApproximation")==0) return SIAApproximationEnum;
    14971541              else if (strcmp(name,"SMBautoregression")==0) return SMBautoregressionEnum;
     
    15151559              else if (strcmp(name,"SealevelAbsolute")==0) return SealevelAbsoluteEnum;
    15161560              else if (strcmp(name,"SealevelEmotion")==0) return SealevelEmotionEnum;
    1517               else if (strcmp(name,"SealevelInertiaTensorXZ")==0) return SealevelInertiaTensorXZEnum;
    1518               else if (strcmp(name,"SealevelInertiaTensorYZ")==0) return SealevelInertiaTensorYZEnum;
    1519               else if (strcmp(name,"SealevelInertiaTensorZZ")==0) return SealevelInertiaTensorZZEnum;
     1561              else if (strcmp(name,"SealevelchangePolarMotionX")==0) return SealevelchangePolarMotionXEnum;
     1562              else if (strcmp(name,"SealevelchangePolarMotionY")==0) return SealevelchangePolarMotionYEnum;
     1563              else if (strcmp(name,"SealevelchangePolarMotionZ")==0) return SealevelchangePolarMotionZEnum;
    15201564              else if (strcmp(name,"SealevelchangePolarMotion")==0) return SealevelchangePolarMotionEnum;
    15211565              else if (strcmp(name,"SealevelNmotion")==0) return SealevelNmotionEnum;
     
    15691613              else if (strcmp(name,"TotalSmbScaled")==0) return TotalSmbScaledEnum;
    15701614              else if (strcmp(name,"TransientArrayParam")==0) return TransientArrayParamEnum;
    1571               else if (strcmp(name,"TransientInput")==0) return TransientInputEnum;
     1615         else stage=14;
     1616   }
     1617   if(stage==14){
     1618              if (strcmp(name,"TransientInput")==0) return TransientInputEnum;
    15721619              else if (strcmp(name,"TransientParam")==0) return TransientParamEnum;
    15731620              else if (strcmp(name,"TransientSolution")==0) return TransientSolutionEnum;
     
    16041651              else if (strcmp(name,"TriangleInterp")==0) return TriangleInterpEnum;
    16051652              else if (strcmp(name,"MaximumNumberOfDefinitions")==0) return MaximumNumberOfDefinitionsEnum;
    1606          else stage=14;
     1653         else stage=15;
    16071654   }
    16081655        /*If we reach this point, the string provided has not been found*/
  • issm/trunk/src/c/shared/Enum/Synchronize.sh

    r26744 r27035  
    193193END
    194194#}}}
     195#Build issmenum.jl {{{
     196#Header
     197cat <<END >  $ISSM_DIR/src/c/shared/Enum/issmenums.jl
     198#   WARNING: DO NOT MODIFY THIS FILE
     199#            this file has been automatically generated by Synchronize.sh
     200#            Please read README for more information
     201
     202@enum IssmEnum begin
     203END
     204cat temp |  awk '{print "\t" $1}' >> $ISSM_DIR/src/c/shared/Enum/issmenums.jl
     205#Move on to EnumToString
     206cat <<END >> $ISSM_DIR/src/c/shared/Enum/issmenums.jl
     207end
     208
     209function EnumToString(enum::IssmEnum)
     210END
     211cat temp |  awk '{print "\tif(enum==" $1 ") return \"" substr($1,1,length($1)-4) "\" end"}' >> $ISSM_DIR/src/c/shared/Enum/issmenums.jl
     212#Move on to StringToEnumx
     213cat <<END >> $ISSM_DIR/src/c/shared/Enum/issmenums.jl
     214end
     215END
     216#}}}
    195217
    196218#vim file
  • issm/trunk/src/c/shared/Exceptions/Exceptions.cpp

    r25836 r27035  
    1515#include <iomanip>
    1616#include "./exceptions.h"
    17 #include "../io/Print/Print.h"
    18 #include "../io/Comm/IssmComm.h"
    19 #include "../MemOps/MemOps.h"
    2017
    2118ErrorException::ErrorException(const string & what_arg){/*{{{*/
     
    3128
    3229}/*}}}*/
    33 ErrorException::ErrorException(const string& what_file, const string& what_function,int what_line, const string& what_arg){/*{{{*/
     30ErrorException::ErrorException(int what_rank,const string& what_file, const string& what_function,int what_line, const string& what_arg){/*{{{*/
    3431
     32        /*Intermediaries*/
    3533        int len;
    3634
    37         len      = strlen(what_arg.c_str())+1;
    38         what_str = new char[len];
    39         memcpy(what_str,what_arg.c_str(),len);
     35        this->rank     = what_rank;
     36        this->file_line= what_line;
    4037
    41         len       = strlen(what_file.c_str())+1;
    42         file_name = new char[len];
    43         memcpy(file_name,what_file.c_str(),len);
     38        len = strlen(what_arg.c_str())+1;
     39        this->what_str = new char[len];
     40        memcpy(this->what_str,what_arg.c_str(),len);
    4441
    45         len           = strlen(what_function.c_str())+1;
    46         function_name = new char[len];
    47         memcpy(function_name,what_function.c_str(),len);
     42        len = strlen(what_file.c_str())+1;
     43        this->file_name = new char[len];
     44        memcpy(this->file_name,what_file.c_str(),len);
    4845
    49         file_line= what_line;
    50         /*When error messages are not shown properly, uncomment the following line*/
    51         this->Report();
     46        len = strlen(what_function.c_str())+1;
     47        this->function_name = new char[len];
     48        memcpy(this->function_name,what_function.c_str(),len);
    5249
     50        /*Uncomment if messages do not print properly*/
     51        //this->Report();
    5352}/*}}}*/
    5453ErrorException::~ErrorException() throw(){/*{{{*/
     
    5857}/*}}}*/
    5958const char* ErrorException::what() const throw(){/*{{{*/
    60         //this->Report();
    6159        return what_str;
    6260}/*}}}*/
     
    6462
    6563        /*WINDOWS*/
    66         if(!function_name || file_line==0){
    67                 _printf_("Error message: " << what());
     64        if(!this->function_name || this->file_line==0){
     65                cerr << "Error message: " << what() << endl;
    6866                return;
    6967        }
    7068
    71         /*recover my_rank and num_procs:*/
    72         int my_rank   = IssmComm::GetRank();
    73         int num_procs = IssmComm::GetSize();
    74 
    75         if(num_procs==1){
    76                 _printf_("\n??? Error in ==> " << file_name << ":" << file_line << "\n");
    77                 _printf_(function_name << " error message: " << what() << "\n\n");
    78         }
    79         else{
    80                 _printf_("\n[" << my_rank<< "] ??? Error using ==> " << file_name << ":" << file_line << "\n");
    81                 _printf_(  "[" << my_rank << "] " << function_name << " error message: " << what() << "\n\n");
    82         }
     69        cerr <<"\n[" << this->rank<< "] ??? Error using ==> " << this->file_name << ":" << this->file_line <<
     70               "\n[" << this->rank<< "] " << this->function_name << " error message: " << what() << "\n" << endl;
    8371
    8472        return;
     
    9179
    9280        /*WINDOWS*/
    93         if(!function_name || file_line==0){
     81        if(!this->function_name || this->file_line==0){
    9482                buffer << " error message: " << this->what_str;
    9583        }
     
    10189        /*Convert std::ostringstream to std::string and then create char* */
    10290        std::string buffer2 = buffer.str();
    103         message = xNew<char>(strlen(buffer2.c_str())+1); sprintf(message,"%s",buffer2.c_str());
     91        message = new char[strlen(buffer2.c_str())+1];
     92        sprintf(message,"%s",buffer2.c_str());
     93
    10494        return message;
    10595}/*}}}*/
  • issm/trunk/src/c/shared/Exceptions/exceptions.h

    r24686 r27035  
    2828#include <sstream>
    2929
    30 /*macros: */
     30/*macros: (should move somewhere else)*/
     31#include "../io/Comm/IssmComm.h"
    3132/* _assert_ {{{*/
    3233/*Assertion macro: do nothing if macro _ISSM_DEBUG_ undefined*/
     
    5051        do{std::ostringstream aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy; \
    5152   aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy << StreamArgs << std::ends; \
    52    throw ErrorException(__FILE__,__func__,__LINE__,aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy.str());}while(0)
     53   throw ErrorException(IssmComm::GetRank(),__FILE__,__func__,__LINE__,aLoNgAnDwEiRdLoCaLnAmeFoRtHiSmAcRoOnLy.str());}while(0)
    5354#endif
    5455/*}}}*/
     
    7879
    7980/*ISSM exception class: */
    80 class ErrorException: public exception { /*{{{*/
     81class ErrorException: public exception{ /*{{{*/
    8182
    8283        char* what_str;
     
    8485        char* file_name;
    8586        int   file_line;
     87        int   rank;
    8688
    8789        public:
    88         ErrorException(const string &what_arg); //for windows
    89         ErrorException(const string &what_file,const string& what_function,int what_line,const string& what_arg);//UNIX
     90        /*Windows*/
     91        ErrorException(const string &what_arg);
     92        /*Linux/macOS*/
     93        ErrorException(int what_rank,const string &what_file,const string& what_function,int what_line,const string& what_arg);
    9094        ~ErrorException() throw();
    9195        virtual const char *what() const throw();
  • issm/trunk/src/c/shared/MemOps/MemOps.h

    r26744 r27035  
    151151template <class T>  T* xMemCpy(T* dest, const T* src, unsigned int size) {/*{{{*/
    152152  assert(dest); assert(src);
    153   #if defined(_HAVE_ADOLC_)
     153  #if defined(_HAVE_ADOLC_) || defined(_HAVE_CODIPACK_)
    154154  for (int i=0; i<size;++i) dest[i]=src[i];
    155155  #else
  • issm/trunk/src/c/shared/Random/randomgenerator.cpp

    r26656 r27035  
    1818
    1919      pseed = new unsigned int;
    20                         *pseed = std::chrono::steady_clock::now().time_since_epoch()/std::chrono::milliseconds(1);
     20                *pseed = std::chrono::steady_clock::now().time_since_epoch()/std::chrono::milliseconds(1);
    2121      a = 1103515245;                  // BSD Formula
    2222      c = 12345;                                             // BSD Formula
     
    2424                        return;
    2525        }/*}}}*/
    26 
    2726  linear_congruential_engine::linear_congruential_engine(unsigned int _a, unsigned int _b, unsigned int _m){/*{{{*/
    2827
    2928      pseed = new unsigned int;
    30                         *pseed = std::chrono::steady_clock::now().time_since_epoch()/std::chrono::milliseconds(1);
     29                *pseed = std::chrono::steady_clock::now().time_since_epoch()/std::chrono::milliseconds(1);
    3130      a = _a;
    3231      c = _b;
     
    3433                        return;
    3534        }/*}}}*/
    36 
    3735        linear_congruential_engine::~linear_congruential_engine(){}
    3836
  • issm/trunk/src/c/shared/io/Marshalling/IoCodeConversions.cpp

    r26744 r27035  
    241241                case 11: return SMBgradientscomponentsEnum;
    242242                case 12: return SMBsemicEnum;   
    243                 case 55: return SMBautoregressionEnum;
     243                case 13: return SMBautoregressionEnum;
    244244                default: _error_("Marshalled SMB code \""<<enum_in<<"\" not supported yet");
    245245        }
     
    255255                case 7: return BasalforcingsIsmip6Enum;
    256256                case 8: return BeckmannGoosseFloatingMeltRateEnum;
     257                case 9: return AutoregressionLinearFloatingMeltRateEnum;
    257258                default: _error_("Marshalled Basal Forcings code \""<<enum_in<<"\" not supported yet");
    258259        }
     
    267268                case 6: return CalvingCrevasseDepthEnum;
    268269                case 7: return CalvingDev2Enum;
     270                case 9: return CalvingParameterizationEnum;
     271                case 8: return CalvingTestEnum;
    269272                default: _error_("Marshalled Calving law code \""<<enum_in<<"\" not supported yet");
    270273        }
     
    274277                case 1: return FrontalForcingsDefaultEnum;
    275278                case 2: return FrontalForcingsRignotEnum;
    276                 case 55: return FrontalForcingsRignotAutoregressionEnum;
     279                case 3: return FrontalForcingsRignotAutoregressionEnum;
    277280                default: _error_("Marshalled Frontalforcings code \""<<enum_in<<"\" not supported yet");
    278281        }
     
    342345                case 2: return SSAApproximationEnum;
    343346                case 3: return L1L2ApproximationEnum;
    344                 case 4: return MLHOApproximationEnum;
     347                case 4: return MOLHOApproximationEnum;
    345348                case 5: return HOApproximationEnum;
    346349                case 6: return FSApproximationEnum;
     
    357360                case 2: return SSAApproximationEnum;
    358361                case 3: return L1L2ApproximationEnum;
    359                 case 4: return MLHOApproximationEnum;
     362                case 4: return MOLHOApproximationEnum;
    360363                case 5: return HOApproximationEnum;
    361364                case 6: return FSApproximationEnum;
  • issm/trunk/src/c/shared/io/Marshalling/Marshalling.cpp

    r26744 r27035  
    9191void RegisterInputFunctor::call(IssmDouble & value){/*{{{*/
    9292        _assert_(this->double_count<size_max);
    93         _assert_(!xIsNan<IssmDouble>(value));
     93
     94        /*Comment out this assert, some parameters are NaN (e.g. abstol) by default*/
     95        //_assert_(!xIsNan<IssmDouble>(value));
     96
    9497        this->tape_codi->registerInput(value);
    9598        #if _CODIPACK_MAJOR_==2
     
    137140}/*}}}*/
    138141void RegisterOutputFunctor::call(IssmDouble & value){/*{{{*/
    139         _assert_(!xIsNan<IssmDouble>(value));
     142        //_assert_(!xIsNan<IssmDouble>(value));
    140143        this->tape_codi->registerOutput(value);
    141144        this->double_count++;
  • issm/trunk/src/c/solutionsequences/convergence.cpp

    r24313 r27035  
    9090                //compute max(du)
    9191                duf=old_uf->Duplicate(); old_uf->Copy(duf); duf->AYPX(uf,-1.0);
    92                 ndu=duf->Norm(NORM_TWO); nduinf=duf->Norm(NORM_INF);
    93                 if (xIsNan<IssmDouble>(ndu) || xIsNan<IssmDouble>(nu)) _error_("convergence criterion is NaN!");
     92                nduinf=duf->Norm(NORM_INF);
     93                if (xIsNan<IssmDouble>(nduinf)) _error_("convergence criterion is NaN!");
    9494
    9595                //clean up
  • issm/trunk/src/c/solutionsequences/solutionsequence_sampling.cpp

    r26744 r27035  
    1313void GaussianVector(Vector<IssmDouble>* ppf,int seed){/*{{{*/
    1414
    15 
    16         /*Intermediaries*/
    17         double      rdnumber;
    18 
    1915        /*Define seed*/
    2016        rnd::linear_congruential_engine random_engine;
    21         if(seed>=0)
    22         {
     17        if(seed>=0){
    2318                int my_rank;
    2419                ISSM_MPI_Comm_rank(ISSM_MPI_COMM_WORLD,&my_rank);
     
    2823
    2924        /* Define univariate distribution */
    30 
    3125        rnd::normal_distribution distribution(0.0,1.0);
    3226
     
    3832        ppf->GetLocalSize(&M);
    3933        for(int i=0;i<M;i++){
    40                 rdnumber = distribution.generator(random_engine);
     34                double rdnumber = distribution.generator(random_engine);
    4135                ppf->SetValue(local_indices[i],rdnumber,INS_VAL);
    4236        }
    4337        ppf->Assemble();
    4438
     39        /*Cleanup*/
     40        random_engine.free_resources();
     41        xDelete<int>(local_indices);
     42        xDelete<IssmDouble>(local_vector);
    4543}/*}}}*/
    4644void solutionsequence_sampling(FemModel* femmodel){
     
    5149  Vector<IssmDouble>*  ug  = NULL;
    5250  Vector<IssmDouble>*  uf  = NULL;
    53   Vector<IssmDouble>*  old_uf  = NULL;     // previous solution vector (for transient)
    54   Vector<IssmDouble>*  pf  = NULL;
     51        Vector<IssmDouble>*  pf  = NULL;
    5552  Vector<IssmDouble>*  df  = NULL;
    5653  Vector<IssmDouble>*  ys=NULL;
     
    6259
    6360  /*parameters:*/
    64   int solution_type, alpha, step, seed, nsize;
    65   IssmDouble phi, tau;
     61  int alpha, seed, nsize;
    6662
    6763  /*Recover parameters: */
    68   femmodel->parameters->FindParam(&solution_type,SolutionTypeEnum);
    6964  femmodel->parameters->FindParam(&seed,SamplingSeedEnum);
    7065  femmodel->parameters->FindParam(&alpha,SamplingAlphaEnum);
    71   femmodel->parameters->FindParam(&tau,SamplingTauEnum);
    72 
    73   /*Recover parameters for transient simulation: */
    74   if(solution_type==TransientSolutionEnum)
    75   {
    76     femmodel->parameters->FindParam(&step,StepEnum);
    77     femmodel->parameters->FindParam(&phi,SamplingPhiEnum);
    78                 if(seed>=0) seed = seed + 13923272*step; // change default seed for transient simulations (by considering an arbitrary shif based on the step number)
    79 
    80     GetSolutionFromInputsx(&ug,femmodel);
    81     Reducevectorgtofx(&uf, ug, femmodel->nodes,femmodel->parameters);
    82     old_uf=uf->Duplicate();
    83   }
    8466
    8567  /*CreateAnalysis*/
     
    10183  Reduceloadx(pf, Kfs, ys);
    10284  delete Kfs;
    103 
    104   /*Copy old solution for transient run */
    105   if(solution_type==TransientSolutionEnum) uf->Copy(old_uf);
    10685
    10786  /* Generate random RHS */
     
    130109  }
    131110
    132   /* Divide results by tau */
    133   uf->Scale(1.0/tau);
    134 
    135   /* Update solution x_{t+1} = phi x_{t} + noise for transient */
    136   if(solution_type==TransientSolutionEnum) uf->AXPY(old_uf,phi);
    137 
    138111  /* Update input */
    139112  Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);
     
    141114
    142115  /*clean-up*/
    143   delete Kff; delete pf; delete df; delete uf; delete ys; delete old_uf;
     116  delete Kff; delete pf; delete df; delete uf; delete ys;
    144117  delete Ml; delete Mscale;
    145118  delete analysis;
  • issm/trunk/src/m/classes/SMBautoregression.m

    r26744 r27035  
    1414                phi               = NaN;
    1515                basin_id          = NaN;
     16                lapserates        = NaN;
     17                elevationbins     = NaN;
     18                refelevation      = NaN;
    1619                steps_per_step    = 1;
    1720                averaging         = 0;
     
    5962                        self.ar_order    = 0.0; %autoregression model of order 0
    6063                end % }}}
    61                 function md = checkconsistency(self,md,solution,analyses)
     64                function md = checkconsistency(self,md,solution,analyses) % {{{
    6265
    6366                        if ismember('MasstransportAnalysis',analyses),
     
    7073                                md = checkfield(md,'fieldname','smb.ar_timestep','numel',1,'NaN',1,'Inf',1,'>=',md.timestepping.time_step); %autoregression time step cannot be finer than ISSM timestep
    7174                                md = checkfield(md,'fieldname','smb.phi','NaN',1,'Inf',1,'size',[md.smb.num_basins,md.smb.ar_order]);
     75
     76                                if (any(isnan(md.smb.refelevation)==0) || numel(md.smb.refelevation)>1)
     77               md = checkfield(md,'fieldname','smb.refelevation','NaN',1,'Inf',1,'>=',0,'size',[1,md.smb.num_basins],'numel',md.smb.num_basins);
     78            end
     79                                [nbas,nbins] = size(md.smb.lapserates);
     80                                if (any(isnan(reshape(md.smb.lapserates,[1,nbas*nbins]))==0) || numel(md.smb.lapserates)>1)
     81                                        md = checkfield(md,'fieldname','smb.lapserates','NaN',1,'Inf',1,'size',[md.smb.num_basins,nbins],'numel',md.smb.num_basins*nbins);
     82                                        md = checkfield(md,'fieldname','smb.elevationbins','NaN',1,'Inf',1,'size',[md.smb.num_basins,nbins-1],'numel',md.smb.num_basins*(nbins-1));
     83                                        if(issorted(md.smb.elevationbins,2)==0)
     84                                                error('md.smb.elevationbins should have rows in order of increasing elevation');
     85                                        end
     86                                elseif (isnan(md.smb.elevationbins(1,1))==0 || numel(md.smb.elevationbins)>1)
     87                                        %elevationbins specified but not lapserates: this will inevitably lead to inconsistencies
     88                                        [nbas,nbins] = size(md.smb.elevationbins);
     89                                        nbins        = nbins+1;
     90                                        md = checkfield(md,'fieldname','smb.lapserates','NaN',1,'Inf',1,'size',[md.smb.num_basins,nbins],'numel',md.smb.num_basins*nbins);
     91                                        md = checkfield(md,'fieldname','smb.elevationbins','NaN',1,'Inf',1,'size',[md.smb.num_basins,nbins-1],'numel',md.smb.num_basins*(nbins-1));
     92                                end
    7293                        end
    7394                        md = checkfield(md,'fieldname','smb.steps_per_step','>=',1,'numel',[1]);
    7495                        md = checkfield(md,'fieldname','smb.averaging','numel',[1],'values',[0 1 2]);
    7596                        md = checkfield(md,'fieldname','smb.requested_outputs','stringrow',1);
    76                 end
     97                end % }}}
    7798                function disp(self) % {{{
    7899                        disp(sprintf('   surface forcings parameters:'));
    79100                        fielddisplay(self,'num_basins','number of different basins [unitless]');
    80101                        fielddisplay(self,'basin_id','basin number assigned to each element [unitless]');
    81                         fielddisplay(self,'beta0','basin-specific intercept values [m ice eq./yr]');
     102                        fielddisplay(self,'beta0','basin-specific intercept values [m ice eq./yr] (if beta_1==0 mean=beta_0/(1-sum(phi)))');
    82103                        fielddisplay(self,'beta1','basin-specific trend values [m ice eq. yr^(-2)]');
    83104                        fielddisplay(self,'ar_order','order of the autoregressive model [unitless]');
     
    85106                        fielddisplay(self,'ar_timestep','time resolution of the autoregressive model [yr]');
    86107                        fielddisplay(self,'phi','basin-specific vectors of lag coefficients [unitless]');
     108                        fielddisplay(self,'lapserates','basin-specific SMB lapse rates applied in each elevation bin, 1 row per basin, 1 column per bin [m ice eq yr^-1 m^-1] (default: no lapse rate)');
     109                        fielddisplay(self,'elevationbins','basin-specific separations between elevation bins, 1 row per basin, 1 column per limit between bins [m] (default: no basin separation)');
     110                        fielddisplay(self,'refelevation','basin-specific reference elevations at which SMB is calculated, and from which SMB is downscaled using lapserates (default: basin mean elevation) [m]');
    87111                        fielddisplay(self, 'steps_per_step', 'number of smb steps per time step');
    88112                        fielddisplay(self, 'averaging', 'averaging methods from short to long steps');
     
    97121                        yts=md.constants.yts;
    98122
    99                         WriteData(fid,prefix,'name','md.smb.model','data',55,'format','Integer');
     123                        templapserates    = md.smb.lapserates;
     124                        tempelevationbins = md.smb.elevationbins;
     125                        temprefelevation  = md.smb.refelevation;
     126                        [nbas,nbins]      = size(md.smb.lapserates);
     127                        if(any(isnan(reshape(md.smb.lapserates,[1,nbas*nbins]))))
     128                                templapserates = zeros(md.smb.num_basins,2);
     129                                disp('      smb.lapserates not specified: set to 0');
     130                           tempelevationbins = zeros(md.smb.num_basins,1); %dummy elevation bins
     131                        end
     132                        if(any(isnan(md.smb.refelevation)))
     133                                temprefelevation = zeros(1,md.smb.num_basins);
     134                                areas = GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y);
     135                                for ii=1:md.smb.num_basins
     136                                        indices = find(md.smb.basin_id==ii);
     137                                        elemsh  = zeros(numel(indices),1);
     138                                        for jj=1:numel(indices)
     139                                                elemsh(jj) = mean(md.geometry.surface(md.mesh.elements(indices(jj),:)));
     140                                        end
     141                                        temprefelevation(ii) = sum(areas(indices).*elemsh)/sum(areas(indices));
     142                                end
     143                                if(any(reshape(md.smb.lapserates,[1,nbas*nbins])~=0))
     144                                        disp('      smb.refelevation not specified: Reference elevations set to mean surface elevation of basins');
     145                                end
     146                        end
     147                        [nbas,nbins] = size(templapserates);
     148
     149                        WriteData(fid,prefix,'name','md.smb.model','data',13,'format','Integer');
    100150                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','num_basins','format','Integer');
    101151                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','ar_order','format','Integer');
     
    106156                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','beta1','format','DoubleMat','name','md.smb.beta1','scale',1./(yts^2),'yts',yts);
    107157                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','phi','format','DoubleMat','name','md.smb.phi','yts',yts);
     158                        WriteData(fid,prefix,'data',templapserates,'format','DoubleMat','name','md.smb.lapserates','scale',1./yts,'yts',yts);
     159                        WriteData(fid,prefix,'data',tempelevationbins,'format','DoubleMat','name','md.smb.elevationbins');
     160                        WriteData(fid,prefix,'data',temprefelevation,'format','DoubleMat','name','md.smb.refelevation');
     161                        WriteData(fid,prefix,'data',nbins,'format','Integer','name','md.smb.num_bins');
    108162                        WriteData(fid,prefix,'object',self,'fieldname','steps_per_step','format','Integer');
    109163                        WriteData(fid,prefix,'object',self,'fieldname','averaging','format','Integer');
  • issm/trunk/src/m/classes/SMBautoregression.py

    r26744 r27035  
    55from project3d import *
    66from WriteData import *
    7 
     7from GetAreas import *
    88
    99class SMBautoregression(object):
     
    2323        self.phi = np.nan
    2424        self.basin_id = np.nan
     25        self.lapserates = np.nan
     26        self.elevationbins = np.nan
     27        self.refelevation = np.nan
    2528        self.steps_per_step = 1
    2629        self.averaging = 0
     
    3841        s += '{}\n'.format(fielddisplay(self, 'num_basins', 'number of different basins [unitless]'))
    3942        s += '{}\n'.format(fielddisplay(self, 'basin_id', 'basin number assigned to each element [unitless]'))
    40         s += '{}\n'.format(fielddisplay(self, 'beta0', 'basin-specific intercept values [m ice eq./yr]'))
     43        s += '{}\n'.format(fielddisplay(self, 'beta0', 'basin-specific intercept values [m ice eq./yr] (if beta_1==0 mean=beta_0/(1-sum(phi)))'))
    4144        s += '{}\n'.format(fielddisplay(self, 'beta1', 'basin-specific trend values [m ice eq. yr^(-2)]'))
    4245        s += '{}\n'.format(fielddisplay(self, 'ar_order', 'order of the autoregressive model [unitless]'))
     
    4447        s += '{}\n'.format(fielddisplay(self, 'ar_timestep', 'time resolution of the autoregressive model [yr]'))
    4548        s += '{}\n'.format(fielddisplay(self, 'phi', 'basin-specific vectors of lag coefficients [unitless]'))
    46         s += '{}\n'.format(fielddisplay(self, 'covmat', 'inter-basin covariance matrix for multivariate normal noise at each time step [m^2 ice eq. yr^(-2)]'))
    47         s += '{}\n'.format(fielddisplay(self, 'randomflag', 'whether to apply real randomness (true) or pseudo-randomness with fixed seed (false)'))
     49        s += '{}\n'.format(fielddisplay(self, 'lapserates', 'basin-specific SMB lapse rates applied in each elevation bin, 1 row per basin, 1 column per bin [m ice eq yr^-1 m^-1] (default: no lapse rate)'))
     50        s += '{}\n'.format(fielddisplay(self, 'elevationbins', 'basin-specific SMB lapse rates applied in range of SMB<0 [m ice eq yr^-1 m^-1] (default: no lapse rate)'))
     51        s += '{}\n'.format(fielddisplay(self, 'refelevation', 'basin-specific reference elevations at which SMB is calculated, and from which SMB is downscaled using lapserates (default: basin mean elevation) [m]'))
    4852        s += '{}\n'.format(fielddisplay(self, 'steps_per_step', 'number of smb steps per time step'))
    4953        s += '{}\n'.format(fielddisplay(self, 'averaging', 'averaging methods from short to long steps'))
     
    9195            md = checkfield(md, 'fieldname', 'smb.num_basins', 'numel', 1, 'NaN', 1, 'Inf', 1, '>', 0)
    9296            md = checkfield(md, 'fieldname', 'smb.basin_id', 'Inf', 1, '>=', 0, '<=', md.smb.num_basins, 'size', [md.mesh.numberofelements])
     97            if len(np.shape(self.beta0)) == 1:
     98                self.beta0 = np.array([self.beta0])
     99                self.beta1 = np.array([self.beta1])
    93100            md = checkfield(md, 'fieldname', 'smb.beta0', 'NaN', 1, 'Inf', 1, 'size', [1, md.smb.num_basins], 'numel', md.smb.num_basins) # Scheme fails if passed as column vector
    94101            md = checkfield(md, 'fieldname', 'smb.beta1', 'NaN', 1, 'Inf', 1, 'size', [1, md.smb.num_basins], 'numel', md.smb.num_basins) # Scheme fails if passed as column vector; NOTE: As opposed to MATLAB implementation, pass list
     
    97104            md = checkfield(md, 'fieldname', 'smb.ar_timestep', 'numel', 1, 'NaN', 1, 'Inf', 1, '>=', md.timestepping.time_step) # Autoregression time step cannot be finer than ISSM timestep
    98105            md = checkfield(md, 'fieldname', 'smb.phi', 'NaN', 1, 'Inf', 1, 'size', [md.smb.num_basins, md.smb.ar_order])
     106           
     107            if(np.any(np.isnan(self.refelevation) is False) or np.size(self.refelevation) > 1):
     108                if len(np.shape(self.refelevation)) == 1:
     109                    self.refelevation = np.array([self.refelevation])
     110                md = checkfield(md, 'fieldname', 'smb.refelevation', 'NaN', 1, 'Inf', 1, '>=', 0, 'size', [1, md.smb.num_basins], 'numel', md.smb.num_basins)
     111
     112            if(np.any(np.isnan(self.lapserates) is False) or np.size(self.lapserates) > 1):
     113                if len(np.shape(self.lapserates)) == 1:
     114                    self.lapserates = np.array([self.lapserates])
     115                    nbins = 1
     116                else:
     117                    nbins = np.shape(self.lapserates)[1]
     118                if len(np.shape(self.elevationbins)) == 1:
     119                    self.elevationbins = np.array([self.elevationbins])
     120                md = checkfield(md, 'fieldname', 'smb.lapserates', 'NaN', 1, 'Inf', 1, 'size', [md.smb.num_basins, nbins], 'numel', md.smb.num_basins*nbins)
     121                md = checkfield(md, 'fieldname', 'smb.elevationbins', 'NaN', 1, 'Inf', 1, 'size', [md.smb.num_basins, nbins-1], 'numel', md.smb.num_basins*(nbins-1))
     122                for rr in range(md.smb.num_basins):
     123                    if(np.all(self.elevationbins[rr,0:-1]<=self.elevationbins[rr,1:])==False):
     124                        raise TypeError('md.smb.elevationbins should have rows in order of increasing elevation')
     125            elif(np.any(np.isnan(self.elevationbins) is False) or np.size(self.elevationbins) > 1):
     126                #elevationbins specified but not lapserates: this will inevitably lead to inconsistencies
     127                if len(np.shape(self.elevationbins)) == 1:
     128                    self.elevationbins = np.array([self.elevationbins])
     129                    nbins = 1
     130                else:
     131                    nbins = np.shape(self.elevationbins)[1]+1
     132                md = checkfield(md, 'fieldname', 'smb.lapserates', 'NaN', 1, 'Inf', 1, 'size', [md.smb.num_basins, nbins], 'numel', md.smb.num_basins*nbins)
     133                md = checkfield(md, 'fieldname', 'smb.elevationbins', 'NaN', 1, 'Inf', 1, 'size', [md.smb.num_basins, nbins-1], 'numel', md.smb.num_basins*(nbins-1))
     134
    99135        md = checkfield(md, 'fieldname', 'smb.steps_per_step', '>=', 1, 'numel', [1])
    100136        md = checkfield(md, 'fieldname', 'smb.averaging', 'numel', [1], 'values', [0, 1, 2])
     
    106142        yts = md.constants.yts
    107143
    108         WriteData(fid, prefix, 'name', 'md.smb.model', 'data', 55, 'format', 'Integer')
     144        templapserates    = np.copy(md.smb.lapserates)
     145        tempelevationbins = np.copy(md.smb.elevationbins)
     146        temprefelevation  = np.copy(md.smb.refelevation)
     147        if(np.any(np.isnan(md.smb.lapserates))):
     148            templapserates = np.zeros((md.smb.num_basins,2))
     149            print('      smb.lapserates not specified: set to 0')
     150            tempelevationbins = np.zeros((md.smb.num_basins,1)) #dummy elevation bins
     151        if(np.any(np.isnan(md.smb.refelevation))):
     152            temprefelevation = np.zeros((md.smb.num_basins)).reshape(1,md.smb.num_basins)
     153            areas = GetAreas(md.mesh.elements, md.mesh.x, md.mesh.y)
     154            for ii, bid in enumerate(np.unique(md.smb.basin_id)):
     155                indices = np.where(md.smb.basin_id == bid)[0]
     156                elemsh = np.zeros((len(indices)))
     157                for jj in range(len(indices)):
     158                    elemsh[jj] = np.mean(md.geometry.surface[md.mesh.elements[indices[jj], :] - 1])
     159                temprefelevation[0, ii] = np.sum(areas[indices] * elemsh) / np.sum(areas[indices])
     160            if(np.any(templapserates != 0)):
     161                print('      smb.refelevation not specified: Reference elevations set to mean surface elevation of basins')
     162        nbins = np.shape(templapserates)[1]
     163
     164        WriteData(fid, prefix, 'name', 'md.smb.model', 'data', 13, 'format', 'Integer')
    109165        WriteData(fid, prefix, 'object', self, 'class', 'smb', 'fieldname', 'num_basins', 'format', 'Integer')
    110166        WriteData(fid, prefix, 'object', self, 'class', 'smb', 'fieldname', 'ar_order', 'format', 'Integer')
    111167        WriteData(fid, prefix, 'object', self, 'class', 'smb', 'fieldname', 'ar_initialtime', 'format', 'Double', 'scale', yts)
    112168        WriteData(fid, prefix, 'object', self, 'class', 'smb', 'fieldname', 'ar_timestep', 'format', 'Double', 'scale', yts)
    113         WriteData(fid, prefix, 'object', self, 'class', 'smb', 'fieldname', 'basin_id', 'data', self.basin_id, 'name', 'md.smb.basin_id', 'format', 'IntMat', 'mattype', 2) # 0-indexed
     169        WriteData(fid, prefix, 'object', self, 'class', 'smb', 'fieldname', 'basin_id', 'data', self.basin_id - 1, 'name', 'md.smb.basin_id', 'format', 'IntMat', 'mattype', 2) # 0-indexed
    114170        WriteData(fid, prefix, 'object', self, 'class', 'smb', 'fieldname', 'beta0', 'format', 'DoubleMat', 'name', 'md.smb.beta0', 'scale', 1 / yts, 'yts', yts)
    115171        WriteData(fid, prefix, 'object', self, 'class', 'smb', 'fieldname', 'beta1', 'format', 'DoubleMat', 'name', 'md.smb.beta1', 'scale', 1 / (yts ** 2), 'yts', yts)
    116172        WriteData(fid, prefix, 'object', self, 'class', 'smb', 'fieldname', 'phi', 'format', 'DoubleMat', 'name', 'md.smb.phi', 'yts', yts)
     173        WriteData(fid, prefix, 'data', templapserates, 'name', 'md.smb.lapserates', 'format', 'DoubleMat', 'scale', 1 / yts, 'yts', yts)
     174        WriteData(fid, prefix, 'data', tempelevationbins, 'name', 'md.smb.elevationbins', 'format', 'DoubleMat')
     175        WriteData(fid, prefix, 'data', temprefelevation, 'name', 'md.smb.refelevation', 'format', 'DoubleMat')
     176        WriteData(fid, prefix, 'data', nbins, 'name', 'md.smb.num_bins', 'format', 'Integer')
    117177        WriteData(fid, prefix, 'object', self, 'fieldname', 'steps_per_step', 'format', 'Integer')
    118178        WriteData(fid, prefix, 'object', self, 'fieldname', 'averaging', 'format', 'Integer')
  • issm/trunk/src/m/classes/SMBpddSicopolis.py

    r25836 r27035  
    129129        WriteData(fid, prefix, 'object', self, 'class', 'smb', 'fieldname', 's0t', 'format', 'DoubleMat', 'mattype', 1)
    130130        WriteData(fid, prefix, 'object', self, 'class', 'smb', 'fieldname', 'rlaps', 'format', 'Double')
    131         WriteData(fid, prefix, 'object', self, 'class', 'smb', 'fieldname', 'monthlytemperatures', 'format', 'DoubleMat', 'mattype', 1, 'timeserieslength', md.mesh.numberofvertices + 1, 'yts', md.constants.yts)
     131        WriteData(fid, prefix, 'object', self, 'class', 'smb', 'fieldname', 'monthlytemperatures', 'format', 'DoubleMat', 'mattype', 1, 'timeserieslength', md.mesh.numberofvertices + 1, 'yts', yts)
    132132        WriteData(fid, prefix, 'object', self, 'class', 'smb', 'fieldname', 'precipitation', 'format', 'DoubleMat', 'mattype', 1, 'scale', 1. / yts, 'timeserieslength', md.mesh.numberofvertices + 1, 'yts', yts)
    133133        WriteData(fid, prefix, 'object', self, 'class', 'smb', 'fieldname', 'temperature_anomaly', 'format', 'DoubleMat', 'mattype', 1, 'timeserieslength', md.mesh.numberofvertices + 1, 'yts', yts)
  • issm/trunk/src/m/classes/basalforcings.m

    r26744 r27035  
    1515                                case 0
    1616                                        self=setdefaultparameters(self);
     17                                case 1
     18                                        self =structtoobj(basalforcings(),varargin{1});
    1719                                otherwise
    1820                                        error('constructor not supported');
  • issm/trunk/src/m/classes/calvingvonmises.m

    r26744 r27035  
    4444                        if (~strcmp(solution,'TransientSolution') | md.transient.ismovingfront==0), return; end
    4545
    46                         md = checkfield(md,'fieldname','calving.stress_threshold_groundedice','>',0,'NaN',1,'Inf',1);
    47                         md = checkfield(md,'fieldname','calving.stress_threshold_floatingice','>',0,'NaN',1,'Inf',1);
     46                        md = checkfield(md,'fieldname','calving.stress_threshold_groundedice','>',0,'NaN',1,'Inf',1,'size','universal');
     47                        md = checkfield(md,'fieldname','calving.stress_threshold_floatingice','>',0,'NaN',1,'Inf',1,'size','universal');
    4848                        md = checkfield(md,'fieldname','calving.min_thickness','>=',0,'NaN',1,'Inf',1,'numel',1);
    4949                end % }}}
     
    5858                        yts=md.constants.yts;
    5959                        WriteData(fid,prefix,'name','md.calving.law','data',2,'format','Integer');
    60                         WriteData(fid,prefix,'object',self,'fieldname','stress_threshold_groundedice','format','DoubleMat','mattype',1);
    61                         WriteData(fid,prefix,'object',self,'fieldname','stress_threshold_floatingice','format','DoubleMat','mattype',1);
     60                        WriteData(fid,prefix,'object',self,'fieldname','stress_threshold_groundedice','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
     61                        WriteData(fid,prefix,'object',self,'fieldname','stress_threshold_floatingice','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
    6262                        WriteData(fid,prefix,'object',self,'fieldname','min_thickness','format','Double');
    6363                end % }}}
  • issm/trunk/src/m/classes/calvingvonmises.py

    r26744 r27035  
    4848            return
    4949
    50         md = checkfield(md, 'fieldname', 'calving.stress_threshold_groundedice', '>', 0, 'nan', 1, 'Inf', 1)
    51         md = checkfield(md, 'fieldname', 'calving.stress_threshold_floatingice', '>', 0, 'nan', 1, 'Inf', 1)
     50        md = checkfield(md, 'fieldname', 'calving.stress_threshold_groundedice', '>', 0, 'nan', 1, 'Inf', 1, 'size', 'universal')
     51        md = checkfield(md, 'fieldname', 'calving.stress_threshold_floatingice', '>', 0, 'nan', 1, 'Inf', 1, 'size', 'universal')
    5252        md = checkfield(md, 'fieldname', 'calving.min_thickness', '>=', 0, 'NaN', 1, 'Inf', 1, 'numel', [1])
    5353
     
    5656
    5757    def marshall(self, prefix, md, fid):  # {{{
     58        yts = md.constants.yts
    5859        WriteData(fid, prefix, 'name', 'md.calving.law', 'data', 2, 'format', 'Integer')
    59         WriteData(fid, prefix, 'object', self, 'fieldname', 'stress_threshold_groundedice', 'format', 'DoubleMat', 'mattype', 1)
    60         WriteData(fid, prefix, 'object', self, 'fieldname', 'stress_threshold_floatingice', 'format', 'DoubleMat', 'mattype', 1)
     60        WriteData(fid, prefix, 'object', self, 'fieldname', 'stress_threshold_groundedice', 'format', 'DoubleMat', 'mattype', 1, 'timeserieslength', md.mesh.numberofvertices + 1, 'yts', yts )
     61        WriteData(fid, prefix, 'object', self, 'fieldname', 'stress_threshold_floatingice', 'format', 'DoubleMat', 'mattype', 1, 'timeserieslength', md.mesh.numberofvertices + 1, 'yts', yts)
    6162        WriteData(fid, prefix, 'object', self, 'fieldname', 'min_thickness', 'format', 'Double')
    6263    # }}}
  • issm/trunk/src/m/classes/clusters/generic.m

    r26744 r27035  
    1919                port          = 0;
    2020                interactive   = 1;
    21                 codepath      = [IssmConfig('ISSM_PREFIX') '/bin'];
     21                codepath      = [issmdir() '/bin'];
    2222                etcpath       = [issmdir() '/etc'];
    2323                executionpath = [issmdir() '/execution'];
  • issm/trunk/src/m/classes/clusters/pfe.m

    r26744 r27035  
    1111                name           = 'pfe'
    1212                login          = '';
    13                 modules        = {'comp-intel/2016.2.181' 'mpt'};
     13                modules        = {'comp-intel/2018.3.222' 'mpi-intel/2018.3.222' 'scicon/app-tools'};
    1414                numnodes       = 20;
    1515                cpuspernode    = 8;
     
    1919                processor      = 'ivy';
    2020                srcpath        = '';
     21                extpkgpath     = '';
    2122                codepath       = '';
    2223                executionpath  = '';
     
    4445                        disp(sprintf('    login: %s',cluster.login));
    4546                        disp(sprintf('    modules: %s',strjoin(cluster.modules,', ')));
    46                         disp(sprintf('    numnodes: %s',cluster.numnodes));
    47                         disp(sprintf('    cpuspernode: %s',cluster.cpuspernode));
     47                        disp(sprintf('    numnodes: %i',cluster.numnodes));
     48                        disp(sprintf('    cpuspernode: %i',cluster.cpuspernode));
    4849                        disp(sprintf('    np: %i',cluster.nprocs()));
    4950                        disp(sprintf('    port: %i',cluster.port));
     
    5253                        disp(sprintf('    processor: %i',cluster.processor));
    5354                        disp(sprintf('    srcpath: %s',cluster.srcpath));
     55                        disp(sprintf('    extpkgpath: %s',cluster.extpkgpath));
    5456                        disp(sprintf('    codepath: %s',cluster.codepath));
    5557                        disp(sprintf('    executionpath: %s',cluster.executionpath));
    5658                        disp(sprintf('    grouplist: %s',cluster.grouplist));
    57                         disp(sprintf('    interactive: %s',cluster.interactive));
     59                        disp(sprintf('    interactive: %i',cluster.interactive));
    5860                        disp(sprintf('    bbftp: %s',cluster.bbftp));
    5961                        disp(sprintf('    numstreams: %s',cluster.numstreams));
     
    173175                        fprintf(fid,'export MPI_GROUP_MAX=64\n\n');
    174176                        fprintf(fid,'export ISSM_DIR="%s"\n',cluster.srcpath); %FIXME
     177                        if cluster.extpkgpath
     178                                fprintf(fid,'export ISSM_EXT_PKG="%s"\n',cluster.extpkgpath);
     179                        end
    175180                        fprintf(fid,'source $ISSM_DIR/etc/environment.sh\n');       %FIXME
    176                         fprintf(fid,'export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$ISSM_DIR/externalpackages/petsc/install/lib"\n');
    177181                        fprintf(fid,'cd %s/%s/\n\n',cluster.executionpath,dirname);
    178182                        if ~isvalgrind,
    179                                 fprintf(fid,'/u/scicon/tools/bin/toss3/several_tries mpiexec -np %i %s/%s %s %s/%s %s\n',cluster.nprocs(),cluster.codepath,executable,solution,cluster.executionpath,dirname,modelname);
     183                                fprintf(fid,'/u/scicon/tools/bin/toss3/several_tries mpiexec -np %i mbind.x -cs -n%i %s/%s %s %s/%s %s\n',cluster.nprocs(),cluster.cpuspernode,cluster.codepath,executable,solution,cluster.executionpath,dirname,modelname);
    180184                        else
    181185                                fprintf(fid,'mpiexec -np %i valgrind --leak-check=full %s/%s %s %s %s\n',cluster.nprocs(),cluster.codepath,executable,solution,[cluster.executionpath '/' dirname],modelname);
  • issm/trunk/src/m/classes/clusters/pfe.py

    r26744 r27035  
    2828        self.name = ''
    2929        self.login = ''
    30         self.modules = ['comp-intel/2016.2.181', 'mpt']
     30        self.modules = ['comp-intel/2018.3.222', 'mpi-intel/2018.3.222', 'scicon/app-tools']
    3131        self.numnodes = 20
    3232        self.cpuspernode = 8
     
    3636        self.processor = 'ivy'
    3737        self.srcpath = ''
     38        self.extpkgpath = ''
    3839        self.codepath = ''
    3940        self.executionpath = ''
     
    7273        s += '    processor: {}\n'.format(self.processor)
    7374        s += '    srcpath: {}\n'.format(self.srcpath)
     75        s += '    extpkgpath: {}\n'.format(self.extpkgpath)
    7476        s += '    codepath: {}\n'.format(self.codepath)
    7577        s += '    executionpath: {}\n'.format(self.executionpath)
     
    177179        fid.write('export MPI_GROUP_MAX=64\n\n')
    178180        fid.write('export ISSM_DIR="{}"\n'.format(self.srcpath)) # FIXME
     181        if self.extpkgpath:
     182            fid.write('export ISSM_EXT_PKG="{}"\n'.format(self.extpkgpath))
    179183        fid.write('source $ISSM_DIR/etc/environment.sh\n') # FIXME
    180         fid.write('export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$ISSM_DIR/externalpackages/petsc/install/lib"\n')
    181184        fid.write('cd {}/{}/\n\n'.format(self.executionpath, dirname))
    182185        fid.write('mpiexec -np {} {}/{} {} {}/{} {}\n'.format(self.nprocs(), self.codepath, executable, solution, self.executionpath, dirname, modelname))
  • issm/trunk/src/m/classes/clusters/saga.py

    r26744 r27035  
    119119
    120120        fid.write('#SBATCH --nodes=%i \n' % self.numnodes)
    121         fid.write('#SBATCH --ntasks-per-node=%i \n' % self.cpuspernode)
     121        fid.write('#SBATCH --ntasks=%i \n' % self.cpuspernode)
    122122        fid.write('#SBATCH --time={}\n'.format(timestring))  #walltime is minutes
    123         fid.write('#SBATCH --mem-per-cpu={}MB\n'.format(int(1000 * self.mem)))  # mem is in MB
     123        fid.write('#SBATCH --mem-per-cpu={}M\n'.format(int(1000 * self.mem)))  # mem is in MB
    124124
    125125        fid.write('#SBATCH --account=%s\n' % self.accountname)
     
    130130        fid.write('module purge\n')
    131131        fid.write('module load CMake/3.15.3-GCCcore-8.3.0\n')
    132         fid.write('module load PETSc/3.12.4-intel-2019b\n')
    133         fid.write('module load ParMETIS/4.0.3-iimpi-2019b\n')
     132        fid.write('module load PETSc/3.12.4-foss-2019b\n')
     133        fid.write('module load ParMETIS/4.0.3-gompi-2019b\n')
    134134        if isvalgrind:
    135135            fid.write('module --ignore-cache load Valgrind/3.16.1-gompi-2019b \n')
     
    138138        if isvalgrind:
    139139            # profiling
    140             #fid.write('mpirun {} --tool=callgrind {}/{} {} {}/{} {} 2>{}.errlog>{}.outlog \n'.format(self.valgrind, self.codepath, executable, solution, self.executionpath, dirname, modelname, modelname, modelname))
     140            #fid.write('srun {} --tool=callgrind {}/{} {} {}/{} {} 2>{}.errlog>{}.outlog \n'.format(self.valgrind, self.codepath, executable, solution, self.executionpath, dirname, modelname, modelname, modelname))
    141141            # leak check
    142             fid.write('mpirun {} --leak-check=full {}/{} {} {}/{} {} 2>{}.errlog>{}.outlog '.format(self.valgrind, self.codepath, executable, solution, self.executionpath, dirname, modelname, modelname, modelname))
     142            fid.write('srun {} --leak-check=full {}/{} {} {}/{} {} 2>{}.errlog>{}.outlog '.format(self.valgrind, self.codepath, executable, solution, self.executionpath, dirname, modelname, modelname, modelname))
    143143        else:
    144             fid.write('time mpirun {}/{} {} {}/{} {}\n'.format(self.codepath, executable, solution, self.executionpath, dirname, modelname))
     144            fid.write('time srun {}/{} {} {}/{} {}\n'.format(self.codepath, executable, solution, self.executionpath, dirname, modelname))
    145145        fid.close()
    146146
  • issm/trunk/src/m/classes/flowequation.js

    r26744 r27035  
    2222                fielddisplay(this,'isSSA','is the Shelfy-Stream Approximation (SSA) used ?');
    2323                fielddisplay(this,'isL1L2','is the L1L2 approximation used ?');
    24                 fielddisplay(this,'isMLHO','is the Mono-Layer Higher-Order approximation used?');
     24                fielddisplay(this,'isMOLHO','is the MOno-Layer Higher-Order (MOLHO) approximation used?');
    2525                fielddisplay(this,'isHO','is the Higher-Order (HO) approximation used ?');
    2626                fielddisplay(this,'isFS','are the Full-FS (FS) equations used ?');
     
    4141
    4242        }// }}}
    43     this.extrude = function(md) {//{{{
    44         this.element_equation=project3d(md,'vector',this.element_equation,'type','element');
    45         this.vertex_equation=project3d(md,'vector',this.vertex_equation,'type','node');
    46         this.borderSSA=project3d(md,'vector',this.borderSSA,'type','node');
    47         this.borderHO=project3d(md,'vector',this.borderHO,'type','node');
    48         this.borderFS=project3d(md,'vector',this.borderFS,'type','node');
    49         return this;
     43        this.extrude = function(md) {//{{{
     44                this.element_equation=project3d(md,'vector',this.element_equation,'type','element');
     45                this.vertex_equation=project3d(md,'vector',this.vertex_equation,'type','node');
     46                this.borderSSA=project3d(md,'vector',this.borderSSA,'type','node');
     47                this.borderHO=project3d(md,'vector',this.borderHO,'type','node');
     48                this.borderFS=project3d(md,'vector',this.borderFS,'type','node');
     49                return this;
    5050    }//}}}
    5151                this.checkconsistency = function(md,solution,analyses) {//{{{
     
    5959                        checkfield(md,'fieldname','flowequation.isSSA','numel',[1],'values',[0, 1]);
    6060                        checkfield(md,'fieldname','flowequation.isL1L2','numel',[1],'values',[0, 1]);
    61                         checkfield(md,'fieldname','flowequation.isMLHO','numel',[1],'values',[0, 1]);
     61                        checkfield(md,'fieldname','flowequation.isMOLHO','numel',[1],'values',[0, 1]);
    6262                        checkfield(md,'fieldname','flowequation.isHO','numel',[1],'values',[0, 1]);
    6363                        checkfield(md,'fieldname','flowequation.isFS','numel',[1],'values',[0, 1]);
     
    9393                        else throw Error('Case not supported yet');
    9494                       
    95                         if (!(this.isSIA | this.isSSA | this.isL1L2 | this.isMLHO | this.isHO | this.isFS)){
     95                        if (!(this.isSIA | this.isSSA | this.isL1L2 | this.isMOLHO | this.isHO | this.isFS)){
    9696                                checkmessage(md,['no element types set for this model']);
    9797                        }
     
    108108                        WriteData(fid,prefix,'object',this,'fieldname','isSSA','format','Boolean');
    109109                        WriteData(fid,prefix,'object',this,'fieldname','isL1L2','format','Boolean');
    110                         WriteData(fid,prefix,'object',this,'fieldname','isMLHO','format','Boolean');
     110                        WriteData(fid,prefix,'object',this,'fieldname','isMOLHO','format','Boolean');
    111111                        WriteData(fid,prefix,'object',this,'fieldname','isHO','format','Boolean');
    112112                        WriteData(fid,prefix,'object',this,'fieldname','isFS','format','Boolean');
     
    138138        this.isSSA                          = 0;
    139139        this.isL1L2                         = 0;
    140         this.isMLHO                         = 0;
     140        this.isMOLHO                         = 0;
    141141        this.isHO                           = 0;
    142142        this.isFS                           = 0;
  • issm/trunk/src/m/classes/flowequation.m

    r26744 r27035  
    99                isSSA                          = 0;
    1010                isL1L2                         = 0;
    11                 isMLHO                         = 0;
     11                isMOLHO                         = 0;
    1212                isHO                           = 0;
    1313                isFS                           = 0;
     
    6060                                if isfield(objstruct,'borderpattyn'),  self.borderHO  = objstruct.borderpattyn;   end;
    6161                                if isfield(objstruct,'borderstokes'),  self.borderFS  = objstruct.borderstokes;   end;
    62                         end
    63 
    64                         %Nov 6 2021
    65                         if any(self.vertex_equation==4)
    66                                 disp(['Monolayer Higher-Order (MLHO) detected in md.flowequation, this is still under development. Please double check your settings.']);
    67                         end
     62
     63                                %May 31 2022
     64                                if isfield(objstruct,'isMLHO')
     65                                        self.isMOLHO = objstruct.isMLHO;
     66                                end
     67                        end
     68
    6869
    6970                end% }}}
     
    104105                        md = checkfield(md,'fieldname','flowequation.isSSA','numel',[1],'values',[0 1]);
    105106                        md = checkfield(md,'fieldname','flowequation.isL1L2','numel',[1],'values',[0 1]);
    106                         md = checkfield(md,'fieldname','flowequation.isMLHO','numel',[1],'values',[0 1]);
     107                        md = checkfield(md,'fieldname','flowequation.isMOLHO','numel',[1],'values',[0 1]);
    107108                        md = checkfield(md,'fieldname','flowequation.isHO','numel',[1],'values',[0 1]);
    108109                        md = checkfield(md,'fieldname','flowequation.isFS','numel',[1],'values',[0 1]);
     
    135136                                error('Case not supported yet');
    136137                        end
    137                         if ~(self.isSIA || self.isSSA || self.isL1L2 || self.isMLHO || self.isHO || self.isFS),
     138                        if ~(self.isSIA || self.isSSA || self.isL1L2 || self.isMOLHO || self.isHO || self.isFS),
    138139                                md = checkmessage(md,['no element types set for this model']);
    139140                        end
     
    153154                        fielddisplay(self,'isSSA','is the Shelfy-Stream Approximation (SSA) used?');
    154155                        fielddisplay(self,'isL1L2','is the L1L2 approximation used?');
    155                         fielddisplay(self,'isMLHO','is the Mono-Layer Higher-Order approximation used?');
     156                        fielddisplay(self,'isMOLHO','is the MOno-Layer Higher-Order (MOLHO) approximation used?');
    156157                        fielddisplay(self,'isHO','is the Higher-Order (HO) approximation used?');
    157158                        fielddisplay(self,'isFS','are the Full-FS (FS) equations used?');
     
    172173                        WriteData(fid,prefix,'object',self,'fieldname','isSSA','format','Boolean');
    173174                        WriteData(fid,prefix,'object',self,'fieldname','isL1L2','format','Boolean');
    174                         WriteData(fid,prefix,'object',self,'fieldname','isMLHO','format','Boolean');
     175                        WriteData(fid,prefix,'object',self,'fieldname','isMOLHO','format','Boolean');
    175176                        WriteData(fid,prefix,'object',self,'fieldname','isHO','format','Boolean');
    176177                        WriteData(fid,prefix,'object',self,'fieldname','isFS','format','Boolean');
     
    197198                        writejsdouble(fid,[modelname '.flowequation.isSSA'],self.isSSA);
    198199                        writejsdouble(fid,[modelname '.flowequation.isL1L2'],self.isL1L2);
    199                         writejsdouble(fid,[modelname '.flowequation.isMLHO'],self.isMLHO);
     200                        writejsdouble(fid,[modelname '.flowequation.isMOLHO'],self.isMOLHO);
    200201                        writejsdouble(fid,[modelname '.flowequation.isHO'],self.isHO);
    201202                        writejsdouble(fid,[modelname '.flowequation.isFS'],self.isFS);
  • issm/trunk/src/m/classes/flowequation.py

    r26744 r27035  
    1919        self.isSSA = 0
    2020        self.isL1L2 = 0
    21         self.isMLHO = 0
     21        self.isMOLHO = 0
    2222        self.isHO = 0
    2323        self.isFS = 0
     
    4646        s += '{}\n'.format(fielddisplay(self, 'isSSA', "is the Shelfy-Stream Approximation (SSA) used?"))
    4747        s += '{}\n'.format(fielddisplay(self, 'isL1L2', "are L1L2 equations used?"))
    48         s += '{}\n'.format(fielddisplay(self, 'isMLHO', "are Mono-layer Higher-Order equations used?"))
     48        s += '{}\n'.format(fielddisplay(self, 'isMOLHO', "are MOno-layer Higher-Order (MOLHO) equations used?"))
    4949        s += '{}\n'.format(fielddisplay(self, 'isHO', "is the Higher-Order (HO) approximation used?"))
    5050        s += '{}\n'.format(fielddisplay(self, 'isFS', "are the Full-FS (FS) equations used?"))
     
    9090        md = checkfield(md, 'fieldname', 'flowequation.isSSA', 'numel', [1], 'values', [0, 1])
    9191        md = checkfield(md, 'fieldname', 'flowequation.isL1L2', 'numel', [1], 'values', [0, 1])
    92         md = checkfield(md, 'fieldname', 'flowequation.isMLHO', 'numel', [1], 'values', [0, 1])
     92        md = checkfield(md, 'fieldname', 'flowequation.isMOLHO', 'numel', [1], 'values', [0, 1])
    9393        md = checkfield(md, 'fieldname', 'flowequation.isHO', 'numel', [1], 'values', [0, 1])
    9494        md = checkfield(md, 'fieldname', 'flowequation.isFS', 'numel', [1], 'values', [0, 1])
     
    121121            raise RuntimeError('Case not supported yet')
    122122
    123         if not (self.isSIA or self.isSSA or self.isL1L2 or self.isMLHO or self.isHO or self.isFS):
     123        if not (self.isSIA or self.isSSA or self.isL1L2 or self.isMOLHO or self.isHO or self.isFS):
    124124            md.checkmessage("no element types set for this model")
    125125        if 'StressbalanceSIAAnalysis' in analyses:
     
    134134        WriteData(fid, prefix, 'object', self, 'fieldname', 'isSSA', 'format', 'Boolean')
    135135        WriteData(fid, prefix, 'object', self, 'fieldname', 'isL1L2', 'format', 'Boolean')
    136         WriteData(fid, prefix, 'object', self, 'fieldname', 'isMLHO', 'format', 'Boolean')
     136        WriteData(fid, prefix, 'object', self, 'fieldname', 'isMOLHO', 'format', 'Boolean')
    137137        WriteData(fid, prefix, 'object', self, 'fieldname', 'isHO', 'format', 'Boolean')
    138138        WriteData(fid, prefix, 'object', self, 'fieldname', 'isFS', 'format', 'Boolean')
  • issm/trunk/src/m/classes/fourierlove.m

    r26744 r27035  
    66classdef fourierlove
    77        properties (SetAccess=public)
    8                 nfreq                       = 0;
    9                 frequencies                 = 0;
    10                 sh_nmax                     = 0;
    11                 sh_nmin                     = 0;
    12                 g0                          = 0;
    13                 r0                          = 0;
    14                 mu0                         = 0;
    15                 Gravitational_Constant      = 0;
    16                 allow_layer_deletion        = 0;
    17                 underflow_tol               = 0;
    18                 integration_steps_per_layer = 0;
    19                 istemporal                  = 0;
    20                 n_temporal_iterations       = 0;
    21                 time                        = 0;
    22                 love_kernels                = 0;
    23                 forcing_type                = 0;
    24                 inner_core_boundary         = 0;
    25                 core_mantle_boundary        = 0;
    26                 complex_computation         = 0;
     8                nfreq                                           = 0;
     9                frequencies                                     = 0;
     10                sh_nmax                                         = 0;
     11                sh_nmin                                         = 0;
     12                g0                                                      = 0;
     13                r0                                                      = 0;
     14                mu0                                                     = 0;
     15                Gravitational_Constant          = 0;
     16                chandler_wobble                         = 0;
     17                allow_layer_deletion            = 0;
     18                underflow_tol                           = 0;
     19                pw_threshold                            = 0;
     20                integration_steps_per_layer     = 0;
     21                istemporal                                      = 0;
     22                n_temporal_iterations           = 0;
     23                time                                            = 0;
     24                love_kernels                            = 0;
     25                forcing_type                            = 0;
     26                inner_core_boundary                     = 0;
     27                core_mantle_boundary            = 0;
     28                complex_computation                     = 0;
    2729
    2830        end
     
    5355                        self.mu0=1e11; % Pa
    5456                        self.Gravitational_Constant=6.67259e-11; % m^3 kg^-1 s^-2
     57                        self.chandler_wobble=0;
    5558                        self.allow_layer_deletion=1;
    5659                        self.underflow_tol=1e-16; %threshold of deep to surface love number ratio to trigger the deletion of layer
     60                        self.pw_threshold=1e-3; %if relative variation across frequencies is smaller than this ratio, the post-widder transform for time-dependent love numbers is bypassed
    5761                        self.integration_steps_per_layer=100;
    5862                        self.istemporal=0;
     
    7478                        fielddisplay(self,'mu0','adimensioning constant for stress (default: 10^11) [Pa]');
    7579                        fielddisplay(self,'Gravitational_Constant','Newtonian constant of gravitation (default: 6.67259e-11 [m^3 kg^-1 s^-2])');
    76                         fielddisplay(self,'allow_layer_deletion','allow for migration of the integration boundary with increasing spherical harmonics degree (default: 1)');
     80                        fielddisplay(self,'chandler_wobble','includes the inertial terms for the chandler wobble in the rotational feedback love numbers, only for forcing_type=11 (default: 0) (/!\ 1 is untested yet)');
     81                        fielddisplay(self,'allow_layer_deletion','allow for migration of the integration boundary with increasing spherical harmonics degree (default: 1)');                   
    7782                        fielddisplay(self,'underflow_tol','threshold of deep to surface love number ratio to trigger the deletion of layers (default: 1e-16)');
     83                        fielddisplay(self,'pw_threshold','if relative variation across frequencies is smaller than this ratio, the post-widder transform for time-dependent love numbers is bypassed (default (1e-3)');
    7884                        fielddisplay(self,'integration_steps_per_layer','number of radial steps to propagate the yi system from the bottom to the top of each layer (default: 100)');
    7985                        fielddisplay(self,'istemporal',{'1 for time-dependent love numbers, 0 for frequency-dependent or elastic love numbers (default: 0)', 'If 1: use fourierlove function build_frequencies_from_time to meet consistency'});
     
    98104                        md = checkfield(md,'fieldname','love.mu0','NaN',1,'Inf',1,'numel',1,'>',0);
    99105                        md = checkfield(md,'fieldname','love.Gravitational_Constant','NaN',1,'Inf',1,'numel',1,'>',0);
     106                        md = checkfield(md,'fieldname','love.chandler_wobble','values',[0 1]);
    100107                        md = checkfield(md,'fieldname','love.allow_layer_deletion','values',[0 1]);
    101108                        md = checkfield(md,'fieldname','love.underflow_tol','NaN',1,'Inf',1,'numel',1,'>',0);
     109                        md = checkfield(md,'fieldname','love.pw_threshold','NaN',1,'Inf',1,'numel',1,'>',0);
    102110                        md = checkfield(md,'fieldname','love.integration_steps_per_layer','NaN',1,'Inf',1,'numel',1,'>',0);
    103111                        md = checkfield(md,'fieldname','love.love_kernels','values',[0 1]);
     
    112120                        if md.love.sh_nmin<=1 & (md.love.forcing_type==1 || md.love.forcing_type==5 || md.love.forcing_type==9)
    113121                                error(['Degree 1 not supported for forcing type ' num2str(md.love.forcing_type) '. Use sh_min>=2 for this kind of calculation.'])
     122                        end
     123
     124                        if md.love.chandler_wobble==1
     125                                disp('Warning, Chandler Wobble in Love number calculator has not been validated yet');
    114126                        end
    115127
     
    137149                        WriteData(fid,prefix,'object',self,'fieldname','mu0','format','Double');
    138150                        WriteData(fid,prefix,'object',self,'fieldname','Gravitational_Constant','format','Double');
     151                        WriteData(fid,prefix,'object',self,'fieldname','chandler_wobble','format','Boolean');
    139152                        WriteData(fid,prefix,'object',self,'fieldname','allow_layer_deletion','format','Boolean');
    140153                        WriteData(fid,prefix,'object',self,'fieldname','underflow_tol','format','Double');
     154                        WriteData(fid,prefix,'object',self,'fieldname','pw_threshold','format','Double');
    141155                        WriteData(fid,prefix,'object',self,'fieldname','integration_steps_per_layer','format','Integer');
    142156                        WriteData(fid,prefix,'object',self,'fieldname','istemporal','format','Boolean');
     
    164178                        for i=1:length(self.time)
    165179                                for j=1:2*self.n_temporal_iterations
    166                                         self.frequencies((i-1)*2*self.n_temporal_iterations +j) = j*log(2)/self.time(i)/2/pi;
     180                                        if self.time(i)==0
     181                                                self.frequencies((i-1)*2*self.n_temporal_iterations +j) =0; % convention to avoid marshalling infinite numbers
     182                                        else
     183                                                self.frequencies((i-1)*2*self.n_temporal_iterations +j) = j*log(2)/self.time(i)/2/pi;
     184                                        end
    167185                                end
    168186                        end
  • issm/trunk/src/m/classes/fourierlove.py

    r26744 r27035  
    2222        self.mu0 = 0
    2323        self.Gravitational_Constant = 0
     24        self.chandler_wobble = 0
    2425        self.allow_layer_deletion = 0
    2526        self.underflow_tol = 0
     27        self.pw_threshold = 0
    2628        self.integration_steps_per_layer = 0
    2729        self.istemporal = 0
     
    5153        s += '{}\n'.format(fielddisplay(self, 'allow_layer_deletion', 'allow for migration of the integration boundary with increasing spherical harmonics degree (default: 1)'))
    5254        s += '{}\n'.format(fielddisplay(self, 'Gravitational_Constant', 'Newtonian constant of gravitation (default: 6.67259e-11 [m^3 kg^-1 s^-2])'))
     55        s += '{}\n'.format(fielddisplay(self, 'chandler_wobble', 'includes the inertial terms for the chandler wobble in the rotational feedback love numbers, only for forcing_type=11 (default: 0) (/!\\ 1 has not been validated yet)'))
    5356        s += '{}\n'.format(fielddisplay(self, 'allow_layer_deletion', 'allow for migration of the integration boundary with increasing spherical harmonics degree (default: 1)'))
    54         s += '{}\n'.format(fielddisplay(self, 'underflow_tol', 'threshold of deep to surface love number ratio to trigger the deletion of layers (default: 1e-16)'))
     57        s += '{}\n'.format(fielddisplay(self, 'pw_threshold', 'if relative variation across frequencies is smaller than this ratio, the post-widder transform for time-dependent love numbers is bypassed (default (1e-3)'))
     58        s += '{}\n'.format(fielddisplay(self, 'chandler_wobble', 'includes the inertial terms for the chandler wobble in the rotational feedback love numbers, only for forcing_type=11 (default: 0) (/!\\ 1 is untested)'))
    5559        s += '{}\n'.format(fielddisplay(self, 'integration_steps_per_layer', 'number of radial steps to propagate the yi system from the bottom to the top of each layer (default: 100)'))
    5660        s += '{}\n'.format(fielddisplay(self, 'istemporal', ['1 for time-dependent love numbers, 0 for frequency-dependent or elastic love numbers (default: 0)', 'If 1: use fourierlove function build_frequencies_from_time to meet consistency']))
     
    8892        self.mu0 = 1e11 # Pa
    8993        self.Gravitational_Constant = 6.67259e-11 # m^3 kg^-1 s^-2
     94        self.chandler_wobble = 0
    9095        self.allow_layer_deletion = 1
    9196        self.underflow_tol = 1e-16 # Threshold of deep to surface love number ratio to trigger the deletion of layer
     97        self.pw_threshold = 1e-3 # If relative variation across frequencies is smaller than this ratio, the post-widder transform for time-dependent love numbers is bypassed
    9298        self.integration_steps_per_layer = 100
    9399        self.istemporal = 0
     
    113119        md = checkfield(md, 'fieldname', 'love.mu0', 'NaN', 1, 'Inf', 1, 'numel', 1, '>', 0)
    114120        md = checkfield(md, 'fieldname', 'love.Gravitational_Constant', 'NaN', 1, 'Inf', 1, 'numel', 1, '>', 0)
     121        md = checkfield(md, 'fieldname', 'love.chandler_wobble', 'values', [0, 1])
    115122        md = checkfield(md, 'fieldname', 'love.allow_layer_deletion', 'values', [0, 1])
    116123        md = checkfield(md, 'fieldname', 'love.underflow_tol', 'NaN', 1, 'Inf', 1, 'numel', 1, '>', 0)
     124        md = checkfield(md, 'fieldname', 'love.pw_threshold', 'NaN', 1, 'Inf', 1, 'numel', 1, '>', 0)
    117125        md = checkfield(md, 'fieldname', 'love.integration_steps_per_layer', 'NaN', 1, 'Inf', 1, 'numel', 1, '>', 0)
    118126        md = checkfield(md, 'fieldname', 'love.love_kernels', 'values', [0, 1])
     
    127135            raise RuntimeError('Degree 1 not supported for forcing type {}. Use sh_min >= 2 for this kind of calculation.'.format(md.love.forcing_type))
    128136
     137        if md.love.chandler_wobble  == 1:
     138            print('Warning: Chandler wobble in Love number calculator has not been validated yet')
     139
    129140        # Need 'litho' material
    130         if not hasattr(md.materials, 'materials') or 'litho' not in md.materials.nature:
     141        if md.materials.__class__.__name__ != 'materials' or 'litho' not in md.materials.nature:
    131142            raise RuntimeError('Need a \'litho\' material to run a Fourier Love number analysis')
    132143
    133         mat = np.where(np.array(nature) == 'litho')[0]
     144        mat = np.where(np.array(md.materials.nature) == 'litho')[0]
    134145        if md.love.forcing_type <= 4:
    135146            md = checkfield(md, 'fieldname', 'love.inner_core_boundary', 'NaN', 1, 'Inf', 1, 'numel', 1, '>', 0, '<=', md.materials[mat].numlayers)
     
    149160        WriteData(fid, prefix, 'object', self, 'fieldname', 'mu0', 'format', 'Double')
    150161        WriteData(fid, prefix, 'object', self, 'fieldname', 'Gravitational_Constant', 'format', 'Double')
     162        WriteData(fid, prefix, 'object', self, 'fieldname', 'chandler_wobble', 'format', 'Boolean')
    151163        WriteData(fid, prefix, 'object', self, 'fieldname', 'allow_layer_deletion', 'format', 'Boolean')
    152164        WriteData(fid, prefix, 'object', self, 'fieldname', 'underflow_tol', 'format', 'Double')
     165        WriteData(fid, prefix, 'object', self, 'fieldname', 'pw_threshold', 'format', 'Double')
    153166        WriteData(fid, prefix, 'object', self, 'fieldname', 'integration_steps_per_layer', 'format', 'Integer')
    154167        WriteData(fid, prefix, 'object', self, 'fieldname', 'istemporal', 'format', 'Boolean')
     
    171184        print('Temporal love numbers: Overriding md.love.nfreq and md.love.frequencies')
    172185        self.nfreq = len(self.time) * 2 * self.n_temporal_iterations
    173         self.frequencies = np.zeros((self.nfreq, 1))
     186        self.frequencies = np.zeros((self.nfreq,))
    174187        for i in range(len(self.time)):
    175188            for j in range(2 * self.n_temporal_iterations):
    176                 self.frequencies[(i - 1) * 2 * self.n_temporal_iterations + j] = j * np.log(2) / self.time[i] / 2 / np.pi
     189                if self.time[i] == 0:
     190                    self.frequencies[(i - 1) * 2 * self.n_temporal_iterations + j] = 0 # Convention to avoid marshalling infinite numbers
     191                else:
     192                    self.frequencies[(i - 1) * 2 * self.n_temporal_iterations + j] = j * np.log(2) / self.time[i] / 2 / np.pi
     193        return self
    177194    #}}}
  • issm/trunk/src/m/classes/frontalforcings.m

    r24313 r27035  
    77        properties (SetAccess=public)
    88                meltingrate   = NaN;
     9                ablationrate   = NaN;
    910        end
    1011        methods
     
    2930                function self = extrude(self,md) % {{{
    3031                        self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node');
     32                        self.ablationrate=project3d(md,'vector',self.ablationrate,'type','node');
    3133                end % }}}
    3234                function self = setdefaultparameters(self) % {{{
    3335
    3436                        meltingrate   = NaN;
     37                        ablationrate   = NaN;
    3538                end % }}}
    3639                function md = checkconsistency(self,md,solution,analyses) % {{{
     
    3942
    4043                        md = checkfield(md,'fieldname','frontalforcings.meltingrate','NaN',1,'Inf',1,'timeseries',1,'>=',0);
     44                        if ~isnan(md.frontalforcings.ablationrate)
     45                                md = checkfield(md,'fieldname','frontalforcings.ablationrate','Inf',1,'timeseries',1);
     46                        end
    4147
    4248                end % }}}
     
    4450                        disp(sprintf('   Frontalforcings parameters:'));
    4551                        fielddisplay(self,'meltingrate','melting rate at given location [m/a]');
     52                        fielddisplay(self,'ablationrate','frontal ablation rate at given location [m/a], it contains both calving and melting');
    4653                end % }}}
    4754                function marshall(self,prefix,md,fid) % {{{
     
    4956                        WriteData(fid,prefix,'name','md.frontalforcings.parameterization','data',1,'format','Integer');
    5057                        WriteData(fid,prefix,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts,'scale',1./yts);
     58                        if ~isnan(md.frontalforcings.ablationrate)
     59                                WriteData(fid,prefix,'object',self,'fieldname','ablationrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts,'scale',1./yts);
     60                        end
    5161                end % }}}
    5262        end
  • issm/trunk/src/m/classes/frontalforcingsrignot.py

    r26744 r27035  
    6464    def marshall(self, prefix, md, fid):  # {{{
    6565        WriteData(fid, prefix, 'name', 'md.frontalforcings.parameterization', 'data', 2, 'format', 'Integer')
    66         WriteData(fid, prefix, 'object', self, 'fieldname', 'basin_id', 'data', self.basin_id, 'name', 'md.frontalforcings.basin_id', 'format', 'IntMat', 'mattype', 2) # 0-indexed
     66        WriteData(fid, prefix, 'object', self, 'fieldname', 'basin_id', 'data', self.basin_id - 1, 'name', 'md.frontalforcings.basin_id', 'format', 'IntMat', 'mattype', 2) # 0-indexed
    6767        WriteData(fid, prefix, 'object', self, 'fieldname', 'num_basins', 'format', 'Integer')
    6868        WriteData(fid, prefix, 'object', self, 'fieldname', 'subglacial_discharge', 'format', 'DoubleMat', 'mattype', 1, 'timeserieslength', md.mesh.numberofvertices + 1, 'yts', md.constants.yts)
  • issm/trunk/src/m/classes/frontalforcingsrignotautoregression.m

    r26744 r27035  
    6666         fielddisplay(self,'basin_id','basin number assigned to each element [unitless]');
    6767         fielddisplay(self,'subglacial_discharge','sum of subglacial discharge for each basin [m/d]');
    68          fielddisplay(self,'beta0','basin-specific intercept values [∘C]');
     68         fielddisplay(self,'beta0','basin-specific intercept values [∘C] (if beta_1==0 mean=beta_0/(1-sum(phi)))');
    6969         fielddisplay(self,'beta1','basin-specific trend values [∘C yr^(-1)]');
    7070         fielddisplay(self,'ar_order','order of the autoregressive model [unitless]');
     
    7575                function marshall(self,prefix,md,fid) % {{{
    7676                        yts=md.constants.yts;
    77                         WriteData(fid,prefix,'name','md.frontalforcings.parameterization','data',55,'format','Integer');
     77                        WriteData(fid,prefix,'name','md.frontalforcings.parameterization','data',3,'format','Integer');
    7878                        WriteData(fid,prefix,'object',self,'class','frontalforcings','fieldname','num_basins','format','Integer');
    7979                        WriteData(fid,prefix,'object',self,'class','frontalforcings','fieldname','subglacial_discharge','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',yts);
  • issm/trunk/src/m/classes/frontalforcingsrignotautoregression.py

    r26744 r27035  
    11# -*- coding: utf-8 -*-
    2 
    32import numpy as np
    4 
    53from checkfield import checkfield
    64from fielddisplay import fielddisplay
    75from MatlabFuncs import *
    86from WriteData import WriteData
     7
    98
    109class frontalforcingsrignotautoregression(object):
     
    3635        s += '{}\n'.format(fielddisplay(self, 'basin_id', 'basin number assigned to each element [unitless]'))
    3736        s += '{}\n'.format(fielddisplay(self, 'subglacial_discharge', 'sum of subglacial discharge for each basin [m/d]'))
    38         s += '{}\n'.format(fielddisplay(self, 'beta0', 'basin-specific intercept values [°C]'))
     37        s += '{}\n'.format(fielddisplay(self, 'beta0', 'basin-specific intercept values [°C] (if beta_1==0 mean=beta_0/(1-sum(phi)))'))
    3938        s += '{}\n'.format(fielddisplay(self, 'beta1', 'basin-specific trend values [°C yr^(-1)]'))
    4039        s += '{}\n'.format(fielddisplay(self, 'ar_order', 'order of the autoregressive model [unitless]'))
     
    4948        self.num_basins = 0
    5049        self.subglacial_discharge = np.nan
    51         self.ar_order = 0.0 # Autoregression model of order 0
     50        self.ar_order = 0.0  # Autoregression model of order 0
    5251        return self
    5352    #}}}
     
    6160        md = checkfield(md, 'fieldname', 'frontalforcings.basin_id', 'Inf', 1, '>=', 0, '<=', md.frontalforcings.num_basins, 'size', [md.mesh.numberofelements])
    6261        md = checkfield(md, 'fieldname', 'frontalforcings.subglacial_discharge', '>=', 0, 'NaN', 1, 'Inf', 1, 'timeseries', 1)
     62        if len(np.shape(self.beta0)) == 1:
     63            self.beta0 = np.array([self.beta0])
     64            self.beta1 = np.array([self.beta1])
    6365        md = checkfield(md, 'fieldname', 'frontalforcings.beta0', 'NaN', 1, 'Inf', 1, 'size', [1, md.frontalforcings.num_basins], 'numel', md.frontalforcings.num_basins)
    6466        md = checkfield(md, 'fieldname', 'frontalforcings.beta1', 'NaN', 1, 'Inf', 1, 'size', [1, md.frontalforcings.num_basins], 'numel', md.frontalforcings.num_basins)
     
    7779    def marshall(self, prefix, md, fid):  # {{{
    7880        yts = md.constants.yts
    79         WriteData(fid, prefix, 'name', 'md.frontalforcings.parameterization', 'data', 55, 'format', 'Integer')
     81        WriteData(fid, prefix, 'name', 'md.frontalforcings.parameterization', 'data', 3, 'format', 'Integer')
    8082        WriteData(fid, prefix, 'object', self, 'class', 'frontalforcings', 'fieldname', 'num_basins', 'format', 'Integer')
    8183        WriteData(fid, prefix, 'object', self, 'class', 'frontalforcings', 'fieldname', 'subglacial_discharge', 'format', 'DoubleMat', 'mattype', 1, 'timeserieslength', md.mesh.numberofvertices + 1, 'yts', yts)
     
    8385        WriteData(fid, prefix, 'object', self, 'class', 'frontalforcings', 'fieldname', 'ar_initialtime', 'format', 'Double', 'scale', yts)
    8486        WriteData(fid, prefix, 'object', self, 'class', 'frontalforcings', 'fieldname', 'ar_timestep', 'format', 'Double', 'scale', yts)
    85         WriteData(fid, prefix, 'object', self, 'class', 'frontalforcings', 'fieldname', 'basin_id', 'data', self.basin_id, 'name', 'md.frontalforcings.basin_id', 'format', 'IntMat', 'mattype', 2) # 0-indexed
     87        WriteData(fid, prefix, 'object', self, 'class', 'frontalforcings', 'fieldname', 'basin_id', 'data', self.basin_id - 1, 'name', 'md.frontalforcings.basin_id', 'format', 'IntMat', 'mattype', 2) # 0-indexed
    8688        WriteData(fid, prefix, 'object', self, 'class', 'frontalforcings', 'fieldname', 'beta0', 'format', 'DoubleMat', 'name', 'md.frontalforcings.beta0')
    8789        WriteData(fid, prefix, 'object', self, 'class', 'frontalforcings', 'fieldname', 'beta1', 'format', 'DoubleMat', 'name', 'md.frontalforcings.beta1', 'scale', 1 / yts, 'yts', yts)
  • issm/trunk/src/m/classes/geometry.py

    r26744 r27035  
    6161
    6262    def marshall(self, prefix, md, fid):  # {{{
    63         length_thickness = len(self.thickness)
     63        if isinstance(self.thickness, (list, np.ndarray)):
     64            length_thickness = len(self.thickness)
     65        else:
     66            length_thickness = 1
     67
    6468        if (length_thickness == md.mesh.numberofvertices) or (length_thickness == md.mesh.numberofvertices + 1):
    6569            WriteData(fid, prefix, 'object', self, 'fieldname', 'thickness', 'format', 'DoubleMat', 'mattype', 1, 'timeserieslength', md.mesh.numberofvertices + 1, 'yts', md.constants.yts)
  • issm/trunk/src/m/classes/groundingline.m

    r25836 r27035  
    99                friction_interpolation = '';
    1010                melt_interpolation     = '';
     11                requested_outputs      = {};
    1112        end
    1213        methods
     
    2526                        self.friction_interpolation= 'SubelementFriction1';
    2627                        self.melt_interpolation    = 'NoMeltOnPartiallyFloating';
     28                        %default output
     29         self.requested_outputs     = {'default'};
    2730
    2831                end % }}}
     
    3235                        md = checkfield(md,'fieldname','groundingline.friction_interpolation','values',{'NoFrictionOnPartiallyFloating' 'SubelementFriction1' 'SubelementFriction2'});
    3336                        md = checkfield(md,'fieldname','groundingline.melt_interpolation','values',{'NoMeltOnPartiallyFloating' 'SubelementMelt1' 'SubelementMelt2' 'FullMeltOnPartiallyFloating'});
     37                        md = checkfield(md,'fieldname','groundingline.requested_outputs','stringrow',1);
    3438
    3539                        if ~strcmp(self.migration,'None') & strcmp(solution,'TransientSolution') & md.transient.isgroundingline==1,
     
    4852
    4953                end % }}}
     54                function list = defaultoutputs(self,md) % {{{
     55     
     56                        list = {'Surface','Base','MaskOceanLevelset'};
     57         
     58      end % }}}
    5059                function disp(self) % {{{
    5160                        disp(sprintf('   grounding line migration parameters:'));
     
    5362                        fielddisplay(self,'friction_interpolation','type of friction interpolation for partially floating elements: ''NoFrictionOnPartiallyFloating'',''SubelementFriction1'', or ''SubelementFriction2''');
    5463                        fielddisplay(self,'melt_interpolation','type of melt interpolation for partially floating elements: ''NoMeltOnPartiallyFloating'',''SubelementMelt1'',''SubelementMelt2'', or ''FullMeltOnPartiallyFloating''');
     64                        fielddisplay(self,'requested_outputs','additional outputs requested');
    5565
    5666                end % }}}
     
    5969                        WriteData(fid,prefix,'data',self.friction_interpolation,'name','md.groundingline.friction_interpolation','format','String');
    6070                        WriteData(fid,prefix,'data',self.melt_interpolation,'name','md.groundingline.melt_interpolation','format','String');
     71                       
     72                        %process requested outputs
     73         outputs = self.requested_outputs;
     74         pos  = find(ismember(outputs,'default'));
     75         if ~isempty(pos),
     76            outputs(pos) = [];                         %remove 'default' from outputs
     77            outputs      = [outputs defaultoutputs(self,md)]; %add defaults
     78         end
     79                        WriteData(fid,prefix,'data',outputs,'name','md.groundingline.requested_outputs','format','StringArray')
    6180                end % }}}
    6281                function savemodeljs(self,fid,modelname) % {{{
    6382               
    6483                        writejsstring(fid,[modelname '.groundingline.migration'],self.migration);
    65                         writejsstring(fid,[modelname '.groundingline.friction_interpolation'],self.migration);
    66                         writejsstring(fid,[modelname '.groundingline.melt_interpolation'],self.migration);
     84                        writejsstring(fid,[modelname '.groundingline.friction_interpolation'],self.friction_interpolation);
     85                        writejsstring(fid,[modelname '.groundingline.melt_interpolation'],self.melt_interpolation);
     86                        writejscellstring(fid,[modelname '.groundingline.requested_outputs'],self.requested_outputs);
    6787
    6888                end % }}}
  • issm/trunk/src/m/classes/groundingline.py

    r26744 r27035  
    1818        self.friction_interpolation = ''
    1919        self.melt_interpolation = ''
     20        self.requested_outptuts = []
    2021
    2122        # Set defaults
     
    2930        s += '{}\n'.format(fielddisplay(self, 'migration', 'type of friction interpolation on partially floating elements: ''SubelementFriction1'', ''SubelementFriction2'', ''NoFrictionOnPartiallyFloating'''))
    3031        s += '{}\n'.format(fielddisplay(self, 'migration', 'type of melt interpolation on partially floating elements: \'SubelementMelt1\', \'SubelementMelt2\', \'NoMeltOnPartiallyFloating\', \'FullMeltOnPartiallyFloating\''))
     32        s += '{}\n'.format(fielddisplay(self, 'requested_outputs', 'additional outputs requested'))
    3133        return s
    3234    # }}}
     35
     36    def defaultoutputs(self, md):  # {{{
     37        return ['Surface', 'Base','MaskOceanLevelset']
     38
     39    #}}}
    3340
    3441    def setdefaultparameters(self):  # {{{
     
    3744        self.friction_interpolation = 'SubelementFriction1'
    3845        self.melt_interpolation = 'NoMeltOnPartiallyFloating'
     46        # Default output
     47        self.requested_outputs = ['default']
    3948
    4049        return self
     
    4554        md = checkfield(md, 'fieldname', 'groundingline.friction_interpolation', 'values', ['SubelementFriction1', 'SubelementFriction2', 'NoFrictionOnPartiallyFloating'])
    4655        md = checkfield(md, 'fieldname', 'groundingline.melt_interpolation', 'values', ['SubelementMelt1', 'SubelementMelt2', 'NoMeltOnPartiallyFloating', 'FullMeltOnPartiallyFloating'])
     56        md = checkfield(md, 'fieldname', 'groundingline.requested_outputs', 'stringrow', 1)
    4757
    4858        if(not m.strcmp(self.migration, 'None') and md.transient.isgroundingline and solution == 'TransientSolution'):
     
    6272        WriteData(fid, prefix, 'data', self.friction_interpolation, 'name', 'md.groundingline.friction_interpolation', 'format', 'String')
    6373        WriteData(fid, prefix, 'data', self.melt_interpolation, 'name', 'md.groundingline.melt_interpolation', 'format', 'String')
     74       
     75        # Process requested outputs
     76        outputs = self.requested_outputs
     77        indices = [i for i, x in enumerate(outputs) if x == 'default']
     78        if len(indices) > 0:
     79            outputscopy = outputs[0:max(0, indices[0] - 1)] + self.defaultoutputs(md) + outputs[indices[0] + 1:]
     80            outputs = outputscopy
     81        WriteData(fid, prefix, 'data', outputs, 'name', 'md.groundingline.requested_outputs', 'format', 'StringArray')
    6482    # }}}
  • issm/trunk/src/m/classes/hydrologyglads.py

    r25836 r27035  
    5858
    5959    def defaultoutputs(self, md):  # {{{
    60         list = ['EffectivePressure', 'HydraulicPotential', 'HydrologySheetThickness', 'ChannelArea']
     60        list = ['EffectivePressure', 'HydraulicPotential', 'HydrologySheetThickness', 'ChannelArea', 'ChannelDischarge']
    6161        return list
    6262    # }}}
  • issm/trunk/src/m/classes/hydrologyshreve.m

    r26744 r27035  
    3535                end % }}}
    3636                function md = checkconsistency(self,md,solution,analyses) % {{{
    37 
    3837                        %Early return
    3938                        if ~ismember('HydrologyShreveAnalysis',analyses) | (strcmp(solution,'TransientSolution') & md.transient.ishydrology==0), return; end
  • issm/trunk/src/m/classes/hydrologytws.m

    r26744 r27035  
    4444                end % }}}
    4545                function marshall(self,prefix,md,fid) % {{{
    46                         WriteData(fid,prefix,'name','md.hydrology.model','data',2,'format','Integer');
     46                        WriteData(fid,prefix,'name','md.hydrology.model','data',6,'format','Integer');
    4747                        WriteData(fid,prefix,'object',self,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
    4848                        outputs = self.requested_outputs;
  • issm/trunk/src/m/classes/hydrologytws.py

    r26744 r27035  
    5151
    5252    def marshall(self, prefix, md, fid):  # {{{
    53         WriteData(fid, prefix, 'name', 'md.hydrology.model', 'data', 2, 'format', 'Integer')
     53        WriteData(fid, prefix, 'name', 'md.hydrology.model', 'data', 6, 'format', 'Integer')
    5454        WriteData(fid, prefix, 'object', self, 'fieldname', 'spcwatercolumn', 'format', 'DoubleMat', 'mattype', 1, 'timeserieslength', md.mesh.numberofvertices + 1, 'yts', md.constants.yts)
    5555        outputs = self.requested_outputs
    5656        pos  = find(ismember(outputs,'default'))
    57         if not len(pos),
     57        if not len(pos):
    5858            outputs[pos] = [];  # remove 'default' from outputs
    5959            outputs.extend(defaultoutputs(self, md)) # add defaults
  • issm/trunk/src/m/classes/initialization.m

    r26744 r27035  
    3939                function md = checkconsistency(self,md,solution,analyses) % {{{
    4040                        if ismember('StressbalanceAnalysis',analyses) & ~(strcmp(solution,'TransientSolution') & md.transient.isstressbalance == 0),
    41                                 if ~(isnan(md.initialization.vx) | isnan(md.initialization.vy)),
     41                                if numel(md.initialization.vx)>1 | numel(md.initialization.vy)>1
    4242                                        md = checkfield(md,'fieldname','initialization.vx','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1]);
    4343                                        md = checkfield(md,'fieldname','initialization.vy','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1]);
     
    5959                                md = checkfield(md,'fieldname','initialization.vy','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1]);
    6060                                %Triangle with zero velocity
    61                                 if any(sum(abs(md.initialization.vx(md.mesh.elements)),2)==0 & sum(abs(md.initialization.vy(md.mesh.elements)),2)==0)
     61                                if any(sum(abs(md.initialization.vx(md.mesh.elements)),2)==0 & sum(abs(md.initialization.vy(md.mesh.elements)),2)==0 & min(md.mask.ice_levelset(md.mesh.elements),[],2)<0)
    6262                                        md = checkmessage(md,'at least one triangle has all its vertices with a zero velocity');
    6363                                end
  • issm/trunk/src/m/classes/inversion.m

    r26744 r27035  
    104104                        %Only SSA, HO and FS are supported right now
    105105                        if strcmp(solution,'StressbalanceSolution')
    106                                 if ~(md.flowequation.isSSA || md.flowequation.isMLHO || md.flowequation.isHO || md.flowequation.isFS || md.flowequation.isL1L2),
    107                                         md = checkmessage(md,['inversion can only be performed for SSA, MLHO, HO or FS ice flow models']);
     106                                if ~(md.flowequation.isSSA || md.flowequation.isMOLHO || md.flowequation.isHO || md.flowequation.isFS || md.flowequation.isL1L2),
     107                                        md = checkmessage(md,['inversion can only be performed for SSA, MOLHO, HO or FS ice flow models']);
    108108                                end
    109109                        end
  • issm/trunk/src/m/classes/inversion.py

    r26744 r27035  
    131131        md = checkfield(md, 'fieldname', 'inversion.step_threshold', 'size', [md.inversion.nsteps])
    132132        md = checkfield(md, 'fieldname', 'inversion.cost_functions', 'size', [num_costfunc], 'values', supportedcostfunctions())
    133         md = checkfield(md, 'fieldname', 'inversion.cost_functions_coefficients', 'size', [md.mesh.numberofvertices, num_costfunc], '>=', 0)
    134         md = checkfield(md, 'fieldname', 'inversion.gradient_scaling', 'size', [md.inversion.nsteps, num_controls])
    135         md = checkfield(md, 'fieldname', 'inversion.min_parameters', 'size', [md.mesh.numberofvertices, num_controls])
    136         md = checkfield(md, 'fieldname', 'inversion.max_parameters', 'size', [md.mesh.numberofvertices, num_controls])
     133        if num_costfunc == 1:
     134            md.inversion.cost_functions_coefficients = np.squeeze(md.inversion.cost_functions_coefficients)
     135            md = checkfield(md, 'fieldname', 'inversion.cost_functions_coefficients', 'size', [md.mesh.numberofvertices], '>=', 0)
     136        else:
     137            md = checkfield(md, 'fieldname', 'inversion.cost_functions_coefficients', 'size', [md.mesh.numberofvertices, num_costfunc], '>=', 0)
     138
     139        if num_controls == 1:
     140            md.inversion.gradient_scaling = np.squeeze(md.inversion.gradient_scaling)
     141            md.inversion.min_parameters = np.squeeze(md.inversion.min_parameters)
     142            md.inversion.max_parameters = np.squeeze(md.inversion.max_parameters)
     143            md = checkfield(md, 'fieldname', 'inversion.gradient_scaling', 'size', [md.inversion.nsteps])
     144            md = checkfield(md, 'fieldname', 'inversion.min_parameters', 'size', [md.mesh.numberofvertices])
     145            md = checkfield(md, 'fieldname', 'inversion.max_parameters', 'size', [md.mesh.numberofvertices])
     146        else:
     147            md = checkfield(md, 'fieldname', 'inversion.gradient_scaling', 'size', [md.inversion.nsteps, num_controls])
     148            md = checkfield(md, 'fieldname', 'inversion.min_parameters', 'size', [md.mesh.numberofvertices, num_controls])
     149            md = checkfield(md, 'fieldname', 'inversion.max_parameters', 'size', [md.mesh.numberofvertices, num_controls])
    137150
    138151        # Only SSA, HO and FS are supported right now
    139152        if solution == 'StressbalanceSolution':
    140             if not (md.flowequation.isSSA or md.flowequation.isMLHO or md.flowequation.isHO or md.flowequation.isFS or md.flowequation.isL1L2):
    141                 md.checkmessage("'inversion can only be performed for SSA, MLHO, HO or FS ice flow models")
     153            if not (md.flowequation.isSSA or md.flowequation.isMOLHO or md.flowequation.isHO or md.flowequation.isFS or md.flowequation.isL1L2):
     154                md.checkmessage("'inversion can only be performed for SSA, MOLHO, HO or FS ice flow models")
    142155        if solution == 'BalancethicknessSolution':
    143156            md = checkfield(md, 'fieldname', 'inversion.thickness_obs', 'size', [md.mesh.numberofvertices], 'NaN', 1, 'Inf', 1)
  • issm/trunk/src/m/classes/levelset.m

    r26744 r27035  
    6262
    6363                        md = checkfield(md,'fieldname','levelset.spclevelset','Inf',1,'timeseries',1);
    64                         md = checkfield(md,'fieldname','levelset.stabilization','values',[0 1 2 5]);
     64                        md = checkfield(md,'fieldname','levelset.stabilization','values',[0 1 2 5 6]);
    6565                        md = checkfield(md,'fieldname','levelset.kill_icebergs','numel',1,'values',[0 1]);
    6666                        md = checkfield(md,'fieldname','levelset.migration_max','numel',1,'NaN',1,'Inf',1,'>',0);
  • issm/trunk/src/m/classes/lovenumbers.m

    r26744 r27035  
    1010        properties (SetAccess=public)
    1111
    12                 %regular love numbers:
    13                 h           = []; %provided by PREM model
    14                 k           = []; %idem
    15                 l           = []; %idem
     12                %loading love numbers:
     13                h               = []; %provided by PREM model
     14                k               = []; %idem
     15                l               = []; %idem
    1616               
    1717                %tidal love numbers for computing rotational feedback:
    18                 th          = [];
    19                 tk          = [];
    20                 tl          = [];
    21                 tk2secular  = 0; %deg 2 secular number.
     18                th            = [];
     19                tk            = [];
     20                tl            = [];
     21                tk2secular    = 0; %deg 2 secular number.
     22                pmtf_colinear = [];
     23                pmtf_ortho    = [];
    2224
    2325                %time/frequency for visco-elastic love numbers
     
    4446                        fielddisplay(self,'tl','tidal load Love number (deg 2)');
    4547                        fielddisplay(self,'tk2secular','secular fluid Love number');
     48                        fielddisplay(self,'pmtf_colinear','Colinear component of the Polar Motion Transfer Function (e.g. x-motion due to x-component perturbation of the inertia tensor)');
     49                        fielddisplay(self,'pmtf_ortho','Orthogonal component of the Polar Motion Transfer Function (couples x and y components, only used for Chandler Wobble)');
     50
    4651
    4752                        fielddisplay(self,'istime','time (default: 1) or frequency love numbers (0)');
     
    6267                        self.tk2secular=0.942;
    6368
     69                        self.pmtf_colinear=0.0;
     70                        self.pmtf_ortho=0.0;
     71                        if maxdeg>=2
     72                                self.pmtf_colinear= (1.0+self.k(3,:))/(1.0-self.tk(3,:)/self.tk2secular); %valid only for elastic regime, not viscous. Also neglects chandler wobble
     73                                self.pmtf_ortho= 0.0;
     74                        end
    6475                        %time:
    6576                        self.istime=1; %temporal love numbers by default
     
    8293                        md = checkfield(md,'fieldname','solidearth.lovenumbers.tl','NaN',1,'Inf',1);
    8394                        md = checkfield(md,'fieldname','solidearth.lovenumbers.tk2secular','NaN',1,'Inf',1);
     95                        md = checkfield(md,'fieldname','solidearth.lovenumbers.pmtf_colinear','NaN',1,'Inf',1);
     96                        md = checkfield(md,'fieldname','solidearth.lovenumbers.pmtf_ortho','NaN',1,'Inf',1);
    8497                        md = checkfield(md,'fieldname','solidearth.lovenumbers.timefreq','NaN',1,'Inf',1);
    8598                        md = checkfield(md,'fieldname','solidearth.lovenumbers.istime','NaN',1,'Inf',1,'values',[0 1]);
     
    91104
    92105                        ntf=length(self.timefreq);
    93                         if( size(self.h,2) ~= ntf | size(self.k,2) ~= ntf | size(self.l,2) ~= ntf | size(self.th,2) ~= ntf | size(self.tk,2) ~= ntf | size(self.tl,2) ~= ntf ),
     106                        if( size(self.h,2) ~= ntf | size(self.k,2) ~= ntf | size(self.l,2) ~= ntf | size(self.th,2) ~= ntf | size(self.tk,2) ~= ntf | size(self.tl,2) ~= ntf | size(self.pmtf_colinear,2) ~= ntf | size(self.pmtf_ortho,2) ~= ntf),
    94107                                error('lovenumbers error message: love numbers should have as many time/frequency steps as the time/frequency vector');
     108                        end
     109
     110                        if self.istime && self.timefreq(1)~=0
     111                                error('temporal love numbers must start with elastic response, i.e timefreq(1)=0');
    95112                        end
    96113
     
    108125                        WriteData(fid,prefix,'object',self,'fieldname','tk','name','md.solidearth.lovenumbers.tk','format','DoubleMat','mattype',1);
    109126                        WriteData(fid,prefix,'object',self,'fieldname','tl','name','md.solidearth.lovenumbers.tl','format','DoubleMat','mattype',1);
     127                        WriteData(fid,prefix,'object',self,'fieldname','pmtf_colinear','name','md.solidearth.lovenumbers.pmtf_colinear','format','DoubleMat','mattype',1);
     128                        WriteData(fid,prefix,'object',self,'fieldname','pmtf_ortho','name','md.solidearth.lovenumbers.pmtf_ortho','format','DoubleMat','mattype',1);
    110129                        WriteData(fid,prefix,'object',self,'data',self.tk2secular,'fieldname','lovenumbers.tk2secular','format','Double');
    111130
  • issm/trunk/src/m/classes/lovenumbers.py

    r26744 r27035  
    1919
    2020    def __init__(self, *args):  #{{{
    21         # Regular love numbers
    22         self.h = []   # Provided by PREM model
    23         self.k = []   # idem
    24         self.l = []   # idem
     21        # Loading love numbers
     22        self.h = [] # Provided by PREM model
     23        self.k = [] # idem
     24        self.l = [] # idem
    2525
    2626        # Tidal love numbers for computing rotational feedback
     
    2828        self.tk = []
    2929        self.tl = []
    30         self.tk2secular = 0  # deg 2 secular number
     30        self.tk2secular = 0 # deg 2 secular number
     31        self.pmtf_colinear = []
     32        self.pmtf_ortho = []
     33        pmtf_colinear   = []
     34        pmtf_ortho      = []
    3135
    3236        # Time/frequency for visco-elastic love numbers
     
    4953        s += '{}\n'.format(fielddisplay(self, 'tl', 'tidal load Love number (deg 2)'))
    5054        s += '{}\n'.format(fielddisplay(self, 'tk2secular', 'secular fluid Love number'))
     55        s += '{}\n'.format(fielddisplay(self, 'pmtf_colinear', 'Colinear component of the Polar Motion Transfer Function (e.g. x-motion due to x-component perturbation of the inertia tensor)'))
     56        s += '{}\n'.format(fielddisplay(self, 'pmtf_ortho', 'Orthogonal component of the Polar Motion Transfer Function (couples x and y components, only used for Chandler Wobble)'))
    5157        s += '{}\n'.format(fielddisplay(self, 'istime', 'time (default: 1) or frequency love numbers (0)'))
    5258        s += '{}\n'.format(fielddisplay(self, 'timefreq', 'time/frequency vector (yr or 1/yr)'))
     59        s += '{}\n'.format(fielddisplay(self, 'pmtf_colinear', 'Colinear component of the Polar Motion Transfer Function (e.g. x-motion due to x-component perturbation of the inertia tensor)'))
     60        s += '{}\n'.format(fielddisplay(self, 'pmtf_ortho', 'Orthogonal component of the Polar Motion Transfer Function (couples x and y components, only used for Chandler Wobble)'))
    5361        return s
    5462    #}}}
     
    6573        # Secular fluid love number
    6674        self.tk2secular = 0.942
     75        self.pmtf_colinear=0.0
     76        self.pmtf_ortho=0.0
     77        if maxdeg>=2:
     78            self.pmtf_colinear= (1.0+self.k[3-1,:])/(1.0-self.tk[3-1,:]/self.tk2secular) #valid only for elastic regime, not viscous. Also neglects chandler wobble
     79            self.pmtf_ortho= 0.0
    6780
     81        self.pmtf_colinear = np.array([0.0]).reshape(-1, 1)
     82        self.pmtf_ortho = np.array([0.0]).reshape(-1, 1)
     83        if maxdeg >= 2:
     84            self.pmtf_colinear = ((1.0 + self.k[2, :]) / (1.0 - self.tk[2, :] / self.tk2secular)).reshape(-1, 1) # Valid only for elastic regime, not viscous. Also neglects chandler wobble.
     85            self.pmtf_ortho = np.array([0.0]).reshape(-1, 1)
    6886        # Time
    6987        self.istime = 1 # Temporal love numbers by default
     
    83101        md = checkfield(md, 'fieldname', 'solidearth.lovenumbers.tl', 'NaN', 1, 'Inf', 1)
    84102        md = checkfield(md, 'fieldname', 'solidearth.lovenumbers.tk2secular', 'NaN', 1, 'Inf', 1)
     103        md = checkfield(md, 'fieldname', 'solidearth.lovenumbers.pmtf_colinear', 'NaN', 1, 'Inf', 1)
     104        md = checkfield(md, 'fieldname', 'solidearth.lovenumbers.pmtf_ortho', 'NaN', 1, 'Inf', 1)
    85105        md = checkfield(md, 'fieldname', 'solidearth.lovenumbers.timefreq', 'NaN', 1, 'Inf', 1)
    86106        md = checkfield(md, 'fieldname', 'solidearth.lovenumbers.istime', 'NaN', 1, 'Inf', 1, 'values', [0, 1])
     
    91111
    92112        ntf = len(self.timefreq)
    93         if (np.shape(self.h)[1] != ntf or np.shape(self.k)[1] != ntf or np.shape(self.l)[1] != ntf or np.shape(self.th)[1] != ntf or np.shape(self.tk)[1] != ntf or np.shape(self.tl)[1] != ntf):
     113        if (np.shape(self.h)[1] != ntf or np.shape(self.k)[1] != ntf or np.shape(self.l)[1] != ntf or np.shape(self.th)[1] != ntf or np.shape(self.tk)[1] != ntf or np.shape(self.tl)[1] != ntf or np.shape(self.pmtf_colinear)[1] != ntf or np.shape(self.pmtf_ortho)[1] != ntf):
    94114            raise ValueError('lovenumbers error message: love numbers should have as many time/frequency steps as the time/frequency vector')
    95115
     116        if self.istime and self.timefreq[0] != 0:
     117            raise ValueError('temporal love numbers must start with elastic response, i.e. timefreq[0] = 0')
    96118        return md
    97119    #}}}
     
    109131        WriteData(fid, prefix, 'object', self, 'fieldname', 'tk', 'name', 'md.solidearth.lovenumbers.tk', 'format', 'DoubleMat', 'mattype', 1)
    110132        WriteData(fid, prefix, 'object', self, 'fieldname', 'tl', 'name', 'md.solidearth.lovenumbers.tl', 'format', 'DoubleMat', 'mattype', 1)
     133        WriteData(fid, prefix, 'object', self, 'fieldname', 'pmtf_colinear', 'name', 'md.solidearth.lovenumbers.pmtf_colinear', 'format', 'DoubleMat', 'mattype', 1)
     134        WriteData(fid, prefix, 'object', self, 'fieldname', 'pmtf_ortho', 'name', 'md.solidearth.lovenumbers.pmtf_ortho', 'format', 'DoubleMat', 'mattype', 1)
    111135        WriteData(fid, prefix, 'object', self, 'data', self.tk2secular, 'fieldname', 'lovenumbers.tk2secular', 'format', 'Double')
     136        WriteData(fid, prefix, 'object', self, 'fieldname', 'pmtf_colinear','name','md.solidearth.lovenumbers.pmtf_colinear','format','DoubleMat','mattype',1);
     137        WriteData(fid, prefix, 'object', self, 'fieldname', 'pmtf_ortho','name','md.solidearth.lovenumbers.pmtf_ortho','format','DoubleMat','mattype',1);
    112138
    113139        if (self.istime):
     
    118144        WriteData(fid, prefix, 'object', self, 'fieldname', 'timefreq', 'name', 'md.solidearth.lovenumbers.timefreq', 'format', 'DoubleMat', 'mattype', 1, 'scale', scale);
    119145    #}}}
    120 
     146 
    121147    def extrude(self, md):  #{{{
    122148        return
  • issm/trunk/src/m/classes/m1qn3inversion.py

    r25836 r27035  
    11import numpy as np
    2 
    32from checkfield import checkfield
    43from fielddisplay import fielddisplay
  • issm/trunk/src/m/classes/massfluxatgate.py

    r24313 r27035  
     1import numpy as np
    12from fielddisplay import fielddisplay
    23from pairoptions import pairoptions
     
    2021        self.definitionstring = ''
    2122        self.profilename = ''
    22         self.segments = float('NaN')
     23        self.segments = np.nan
    2324
    2425    #set defaults
  • issm/trunk/src/m/classes/matdamageice.py

    r26744 r27035  
    5757        s += '{}\n'.format(fielddisplay(self, 'rheology_law', 'law for the temperature dependance of the rheology: \'None\', \'BuddJacka\', \'Cuffey\', \'CuffeyTemperate\', \'Paterson\', \'Arrhenius\' or \'LliboutryDuval\''))
    5858        s += '{}\n'.format(fielddisplay(self, 'earth_density', 'Mantle density [kg m^-3]'))
    59         return string
     59        return s
    6060    #}}}
    6161
     
    9393        # Thermal exchange velocity (ice-water interface) (m/s)
    9494        self.thermal_exchange_velocity = 1.00e-4
    95         # Rheology law: what is the temperature dependence of B with T 
     95        # Rheology law: what is the temperature dependence of B with T
    9696        # available: none, paterson and arrhenius
    9797        self.rheology_law = 'Paterson'
  • issm/trunk/src/m/classes/materials.m

    r26744 r27035  
    264264                                        end
    265265                                        ind=find(md.materials.issolid==0);
    266                                         if sum(ismember(diff(ind),1)>=1) %if there are at least two consecutive indices that contain issolid = 0
    267                                                 error(['Fluid layers detected at layers #', num2str(ind'), ', but having 2 or more adjacent fluid layers is not supported yet. Consider merging them.'])
    268                                         end
     266                                        %if sum(ismember(diff(ind),1)>=1) %if there are at least two consecutive indices that contain issolid = 0
     267                                        %               error(['Fluid layers detected at layers #', num2str(ind'), ', but having 2 or more adjacent fluid layers is not supported yet. Consider merging them.'])
     268                                        %end
    269269
    270270                                case 'hydro'
  • issm/trunk/src/m/classes/materials.py

    r26744 r27035  
    11import numpy as np
    2 
    32from checkfield import checkfield
    43from fielddisplay import fielddisplay
     
    173172                self.rheology_n = 3
    174173            elif nat == 'litho':
    175                 # We default to a configuration that enables running GIA 
     174                # We default to a configuration that enables running GIA
    176175                # solutions using giacaron and/or giaivins
    177176                self.numlayers = 2
    178177
    179                 # Center of the earth (approximation, must not be 0), then the 
     178                # Center of the earth (approximation, must not be 0), then the
    180179                # lab (lithosphere/asthenosphere boundary) then the surface
    181180                # (with 1d3 to avoid numerical singularities)
     
    250249                    raise RuntimeError('First layer must be solid (issolid[0] > 0 AND lame_mu[0] > 0). Add a weak inner core if necessary.')
    251250                ind = np.where(md.materials.issolid == 0)[0]
    252                 if np.sum(np.in1d(np.diff(ind),1) >= 1): # If there are at least two consecutive indices that contain issolid = 0
    253                     raise RuntimeError('Fluid layers detected at layers #' + indices + ', but having 2 or more adjacent fluid layers is not supported yet. Consider merging them.')
     251                #if np.sum(np.in1d(np.diff(ind),1) >= 1): # If there are at least two consecutive indices that contain issolid = 0
     252                #    raise RuntimeError('Fluid layers detected at layers #' + indices + ', but having 2 or more adjacent fluid layers is not supported yet. Consider merging them.')
    254253
    255254            elif nat == 'hydro':
     
    295294                WriteData(fid, prefix, 'object', self, 'class', 'materials', 'fieldname', 'density', 'format', 'DoubleMat', 'mattype', 3)
    296295                WriteData(fid, prefix, 'object', self, 'class', 'materials', 'fieldname', 'viscosity', 'format', 'DoubleMat', 'mattype', 3)
    297                 WriteData(fid, prefix, 'object', self, 'class', 'materials', 'fieldname', 'rheologymodel', 'format', 'DoubleMat', 'mattype', 3) 
     296                WriteData(fid, prefix, 'object', self, 'class', 'materials', 'fieldname', 'rheologymodel', 'format', 'DoubleMat', 'mattype', 3)
    298297                WriteData(fid, prefix, 'object', self, 'class', 'materials', 'fieldname', 'burgers_viscosity', 'format', 'DoubleMat', 'mattype', 3)
    299298                WriteData(fid, prefix, 'object', self, 'class', 'materials', 'fieldname', 'burgers_mu', 'format', 'DoubleMat', 'mattype', 3)
  • issm/trunk/src/m/classes/model.m

    r26744 r27035  
    928928                        x_edges = 0.5*(md.mesh.x(edges(:,1)) + md.mesh.x(edges(:,2)));
    929929                        y_edges = 0.5*(md.mesh.y(edges(:,1)) + md.mesh.y(edges(:,2)));
    930                         md2.mesh.x = [md2.mesh.x;x_edges];
    931                         md2.mesh.y = [md2.mesh.y;y_edges];
    932                         md2.mesh.elements = [...
     930                        xnew = [md2.mesh.x;x_edges];
     931                        ynew = [md2.mesh.y;y_edges];
     932                        indexnew = [...
    933933                                index(:,1)          nbv+edges_tria(:,3) nbv+edges_tria(:,2);...
    934934                                nbv+edges_tria(:,2) nbv+edges_tria(:,3) nbv+edges_tria(:,1);...
    935935                                nbv+edges_tria(:,2) nbv+edges_tria(:,1) index(:,3);...
    936936                                nbv+edges_tria(:,3) index(:,2)          nbv+edges_tria(:,1)];
    937                         md2.mesh.numberofelements = 4*nbe;
    938                         md2.mesh.numberofvertices = nbv + size(edges,1);
     937                        %md2.mesh.numberofelements = 4*nbe;
     938                        %md2.mesh.numberofvertices = nbv + size(edges,1);
     939
     940                        %Call Bamg to update other mesh properties
     941                        [bamgmesh_out bamggeom_out]=BamgConvertMesh(indexnew,xnew,ynew);
     942                        md2.mesh.x              = bamgmesh_out.Vertices(:,1);
     943                        md2.mesh.y              = bamgmesh_out.Vertices(:,2);
     944                        md2.mesh.elements       = bamgmesh_out.Triangles(:,1:3);
     945                        md2.mesh.edges          = bamgmesh_out.IssmEdges;
     946                        md2.mesh.segments       = bamgmesh_out.IssmSegments(:,1:3);
     947                        md2.mesh.segmentmarkers = bamgmesh_out.IssmSegments(:,4);
     948                        md2.mesh.numberofelements = size(md2.mesh.elements,1);
     949                        md2.mesh.numberofvertices = length(md2.mesh.x);
     950                        md2.mesh.numberofedges    = size(md2.mesh.edges,1);
     951                        md2.mesh.vertexonboundary = zeros(md2.mesh.numberofvertices,1); md2.mesh.vertexonboundary(md2.mesh.segments(:,1:2)) = 1;
     952
     953                        %Deal with boudary
     954                        md2.mesh.vertexonboundary = [md.mesh.vertexonboundary;sum(md.mesh.vertexonboundary(edges),2)==2];
     955                        md2.mesh.elementconnectivity=bamgmesh_out.ElementConnectivity;
     956                        md2.mesh.elementconnectivity(find(isnan(md2.mesh.elementconnectivity)))=0;
    939957                        disp(['   Old number of elements: ' num2str(nbe)]);
    940958                        disp(['   New number of elements: ' num2str(4*nbe)]);
     
    17341752
    17351753                end % }}}
    1736                 function savemodeljs(md,modelname,websiteroot,varargin) % {{{
    1737                
    1738                         %the goal of this routine is to save the model as a javascript array that can be included in any html
    1739                         %file:
    1740 
    1741                         options=pairoptions(varargin{:});
    1742                         optimization=getfieldvalue(options,'optimize',0);
    1743 
    1744                        
    1745                         %disp:
    1746                         disp(['saving model ''' modelname ''' in file ' websiteroot '/js/' modelname '.js']);
    1747 
    1748                         %open file for writing and declare the model:
    1749                         fid=fopen([websiteroot '/js/' modelname '.js'],'w');
    1750                         fprintf(fid,'var %s=new model();\n',modelname);
    1751 
    1752                         %now go through all the classes and fwrite all the corresponding fields:
    1753                        
    1754                         fields=properties('model');
     1754                function saveasstruct(md,filename) % {{{
     1755
     1756                        fields=sort(properties('model')); %sort fields so that comparison of binary files is easier
     1757                        disp('Converting all model fields to struct...');
     1758                        warning off MATLAB:structOnObject
    17551759                        for i=1:length(fields),
    17561760                                field=fields{i};
    1757 
    1758                                 %Some properties do not need to be saved
    1759                                 if ismember(field,{'results','cluster' }),
    1760                                         continue;
    1761                                 end
    1762 
    1763                                 %some optimization:
    1764                                 if optimization==1,
    1765                                         %optimize for plotting only:
    1766                                         if ~ismember(field,{'geometry','mesh','mask'}),
    1767                                                 continue;
    1768                                         end
    1769                                 end
    1770 
    1771                                 %Check that current field is an object
    1772                                 if ~isobject(md.(field))
    1773                                         error(['field ''' char(field) ''' is not an object']);
    1774                                 end
    1775 
    1776                                 %savemodeljs for current object
    1777                                 %disp(['javascript saving ' field '...']);
    1778                                 savemodeljs(md.(field),fid,modelname);
    1779                         end
    1780 
    1781                         %done, close file:
    1782                         fclose(fid);
     1761                                md.(field) = struct(md.(field));
     1762                        end
     1763                        disp('Converting model to struct...');
     1764                        md=struct(md);
     1765                        warning on MATLAB:structOnObject
     1766                        disp(['Saving as ' filename '...']);
     1767                        save(filename,'md','-v7.3')
     1768                end % }}}
     1769function savemodeljs(md,modelname,websiteroot,varargin) % {{{
     1770
     1771        %the goal of this routine is to save the model as a javascript array that can be included in any html
     1772        %file:
     1773
     1774        options=pairoptions(varargin{:});
     1775        optimization=getfieldvalue(options,'optimize',0);
     1776
     1777
     1778        %disp:
     1779        disp(['saving model ''' modelname ''' in file ' websiteroot '/js/' modelname '.js']);
     1780
     1781        %open file for writing and declare the model:
     1782        fid=fopen([websiteroot '/js/' modelname '.js'],'w');
     1783        fprintf(fid,'var %s=new model();\n',modelname);
     1784
     1785        %now go through all the classes and fwrite all the corresponding fields:
     1786
     1787        fields=properties('model');
     1788        for i=1:length(fields),
     1789                field=fields{i};
     1790
     1791                %Some properties do not need to be saved
     1792                if ismember(field,{'results','cluster' }),
     1793                        continue;
    17831794                end
     1795
     1796                %some optimization:
     1797                if optimization==1,
     1798                        %optimize for plotting only:
     1799                        if ~ismember(field,{'geometry','mesh','mask'}),
     1800                                continue;
     1801                        end
     1802                end
     1803
     1804                %Check that current field is an object
     1805                if ~isobject(md.(field))
     1806                        error(['field ''' char(field) ''' is not an object']);
     1807                end
     1808
     1809                %savemodeljs for current object
     1810                %disp(['javascript saving ' field '...']);
     1811                savemodeljs(md.(field),fid,modelname);
    17841812        end
    1785  end
     1813
     1814        %done, close file:
     1815        fclose(fid);
     1816end
     1817        end
     1818end
  • issm/trunk/src/m/classes/model.py

    r26744 r27035  
    823823            md.inversion.max_parameters = project2d(md, md.inversion.max_parameters, md.mesh.numberoflayers)
    824824        if md.smb.__class__.__name__ == 'SMBforcing' and not np.isnan(md.smb.mass_balance).all():
    825                 md.smb.mass_balance = project2d(md, md.smb.mass_balance, md.mesh.numberoflayers)
     825            md.smb.mass_balance = project2d(md, md.smb.mass_balance, md.mesh.numberoflayers)
    826826        elif md.smb.__class__.__name__ == 'SMBhenning' and not np.isnan(md.smb.smbref).all():
    827                 md.smb.smbref = project2d(md, md.smb.smbref, md.mesh.numberoflayers)
     827            md.smb.smbref = project2d(md, md.smb.smbref, md.mesh.numberoflayers)
    828828
    829829        # Results
  • issm/trunk/src/m/classes/pairoptions.py

    r26744 r27035  
    1111
    1212    def __init__(self, *arg):  # {{{
    13         self.functionname = ''
     13        #self.functionname = ''
    1414        self.list = OrderedDict()
    1515
    1616        #get calling function name
    17         import inspect
    18         if len(inspect.stack()) > 1:
    19             self.functionname = inspect.stack()[1][3]
     17        #import inspect
     18        #if len(inspect.stack()) > 1:
     19        #self.functionname = inspect.stack()[1][3]
     20        import traceback
     21        try:
     22            self.functionname = traceback.extract_stack(limit=2)[0][2]
     23        except IndexError:
     24            pass  #this is probably similar to the previous if treatment (but faster)
    2025
    2126        #initialize list
     
    98103        """
    99104
    100         disp(['WARNING: pairoptions::displayunused is not yet implemented'])
     105        print('WARNING: pairoptions::displayunused is not yet implemented')
    101106    # }}}
     107
    102108    def exist(self, field):  # {{{
    103109        """EXIST - check if the option exists
  • issm/trunk/src/m/classes/regionaloutput.py

    r24313 r27035  
    2525
    2626        self.name = ''
     27        self.model= ''
    2728        self.definitionstring = ''
    2829        self.outputnamestring = ''
    29         self.mask = float('NaN')
     30        self.mask = np.nan
    3031        self.maskexpstring = ''
    3132
     
    4647                self.setmaskfromexp(modelname)
    4748
    48         if (len(self.mask) <= 1 & np.any(np.isnan(self.mask))):
    49             error('regionaloutput error message: ''mask'' field or ''maskexpstring'' and ''model'' fields should be defined!')
     49        # if (len(self.mask) <= 1 & np.any(np.isnan(self.mask))):
     50        #     raise IOError('regionaloutput error message: ''mask'' field or ''maskexpstring'' and ''model'' fields should be defined!')
    5051
    5152    #}}}
     
    7677        return self
    7778    # }}}
     79
    7880    def checkconsistency(self, md, solution, analyses):  # {{{
    7981
  • issm/trunk/src/m/classes/results.py

    r25836 r27035  
    143143
    144144    def __getattr__(self, key):  #{{{
    145         if len(self.steps) == 1:
    146             return getattr(self.steps[0], key)
    147         else:
    148             raise Exception('<results>.<solution> error: Currently, can only get a field if we are not working with a transient solution.')
     145        # NOTE: Currently only returning value from first frame of transient solution (see retrieval of md.results.TransientSolution.BedGRD in test2051.py for justification)
     146        return getattr(self.steps[0], key)
     147
     148        # Original code
     149        # if len(self.steps) == 1:
     150        #     return getattr(self.steps[0], key)
     151        # else:
     152        #     raise Exception('<results>.<solution> error: Currently, can only get a field if we are not working with a transient solution.')
    149153    #}}}
    150154
  • issm/trunk/src/m/classes/rifts.py

    r24313 r27035  
    6767
    6868        numpairs = 0
    69         for rift in self.riftstruct:
    70             numpairs += np.size(rift['penaltypairs'], axis=0)
     69        if numrifts > 0:
     70            for rift in self.riftstruct:
     71                numpairs += np.size(rift['penaltypairs'], axis=0)
    7172
    72     # Convert strings in riftstruct to hard coded numbers
    73         FillDict = {'Air': 0,
    74                     'Ice': 1,
    75                     'Melange': 2,
    76                     'Water': 3}
    77         for rift in self.riftstruct:
    78             if rift['fill'] in ['Air', 'Ice', 'Melange', 'Water']:
    79                 rift['fill'] = FillDict[rift['fill']]
     73            # Convert strings in riftstruct to hard coded numbers
     74            FillDict = {'Air': 0,
     75                        'Ice': 1,
     76                        'Melange': 2,
     77                        'Water': 3}
     78            for rift in self.riftstruct:
     79                if rift['fill'] in ['Air', 'Ice', 'Melange', 'Water']:
     80                    rift['fill'] = FillDict[rift['fill']]
    8081
    81     # 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.
    82         data = np.zeros((numpairs, 12))
    83         count = 0
    84         for rift in self.riftstruct:
    85             numpairsforthisrift = np.size(rift['penaltypairs'], 0)
    86             data[count:count + numpairsforthisrift, 0:7] = rift['penaltypairs']
    87             data[count:count + numpairsforthisrift, 7] = rift['fill']
    88             data[count:count + numpairsforthisrift, 8] = rift['friction']
    89             data[count:count + numpairsforthisrift, 9] = rift['fraction']
    90             data[count:count + numpairsforthisrift, 10] = rift['fractionincrement']
    91             data[count:count + numpairsforthisrift, 11] = rift['state'].reshape(-1)
    92             count += numpairsforthisrift
    93 
     82            # 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.
     83            data = np.zeros((numpairs, 12))
     84            count = 0
     85            for rift in self.riftstruct:
     86                numpairsforthisrift = np.size(rift['penaltypairs'], 0)
     87                data[count:count + numpairsforthisrift, 0:7] = rift['penaltypairs']
     88                data[count:count + numpairsforthisrift, 7] = rift['fill']
     89                data[count:count + numpairsforthisrift, 8] = rift['friction']
     90                data[count:count + numpairsforthisrift, 9] = rift['fraction']
     91                data[count:count + numpairsforthisrift, 10] = rift['fractionincrement']
     92                data[count:count + numpairsforthisrift, 11] = rift['state'].reshape(-1)
     93                count += numpairsforthisrift
     94        else:
     95            data = np.zeros((numpairs, 12))
    9496        WriteData(fid, prefix, 'data', numrifts, 'name', 'md.rifts.numrifts', 'format', 'Integer')
    9597        WriteData(fid, prefix, 'data', data, 'name', 'md.rifts.riftstruct', 'format', 'DoubleMat', 'mattype', 3)
  • issm/trunk/src/m/classes/sampling.m

    r26744 r27035  
    99                tau               = 0;
    1010                beta              = NaN;
    11                 phi               = 0;
     11                phi               = NaN;
    1212                alpha             = 0;
    1313                robin             = 0;
     
    3030                        disp(sprintf('\n      %s','Parameters of PDE operator (kappa^2 I-Laplacian)^(alpha/2)(tau):'));
    3131                        fielddisplay(self,'kappa','coefficient of the identity operator');
    32                         fielddisplay(self,'tau','scaling coefficient of the solution (default: 1.0)');
     32                        fielddisplay(self,'tau','scaling coefficient of the solution');
    3333                        fielddisplay(self,'alpha','exponent in PDE operator, (default: 2.0, BiLaplacian covariance operator)');
    3434
     
    4747                function self = setdefaultparameters(self) % {{{
    4848
    49                         %Scaling coefficient
    50                         self.tau=1;
    51 
    5249                        %Apply Robin boundary conditions
    5350                        self.robin=0;
    54 
    55                         %Temporal correlation factor
    56                         self.phi=0;
    5751
    5852                        %Exponent in fraction SPDE (default: 2, biLaplacian covariance
     
    7771
    7872                        md = checkfield(md,'fieldname','sampling.kappa','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1],'>',0);
    79                         md = checkfield(md,'fieldname','sampling.tau','NaN',1,'Inf',1,'numel',1,'>',0);
     73                        md = checkfield(md,'fieldname','sampling.tau','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1],'>',0);
    8074                        md = checkfield(md,'fieldname','sampling.robin','numel',1,'values',[0 1]);
    8175                        if(md.sampling.robin)
    8276                                md = checkfield(md,'fieldname','sampling.beta','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices 1],'>',0);
    83                         end
    84                         md = checkfield(md,'fieldname','sampling.phi','NaN',1,'Inf',1,'numel',1,'>=',0);
     77            end
    8578                        md = checkfield(md,'fieldname','sampling.alpha','NaN',1,'Inf',1,'numel',1,'>',0);
    8679                        md = checkfield(md,'fieldname','sampling.seed','NaN',1,'Inf',1,'numel',1);
     
    9184
    9285                        WriteData(fid,prefix,'object',self,'fieldname','kappa','format','DoubleMat','mattype',1);
    93                         WriteData(fid,prefix,'object',self,'fieldname','tau','format','Double');
     86                        WriteData(fid,prefix,'object',self,'fieldname','tau','format','DoubleMat','mattype',1);
    9487                        WriteData(fid,prefix,'object',self,'fieldname','beta','format','DoubleMat','mattype',1);
    95                         WriteData(fid,prefix,'object',self,'fieldname','phi','format','Double');
     88                        WriteData(fid,prefix,'object',self,'fieldname','phi','format','DoubleMat','mattype',1);
    9689                        WriteData(fid,prefix,'object',self,'fieldname','alpha','format','Integer');
    9790                        WriteData(fid,prefix,'object',self,'fieldname','robin','format','Boolean');
     
    110103
    111104                        nu = self.alpha-1;
    112                         KAPPA = sqrt(8*nu)/lc;
    113                         TAU = sqrt(gamma(nu)/(gamma(self.alpha)*(4*pi)*KAPPA^(2*nu)*sigma^2));
    114                         md.sampling.kappa = KAPPA*ones(md.mesh.numberofvertices,1);
    115                         md.sampling.tau = TAU;
     105                        KAPPA = sqrt(8*nu)./lc;
     106                        TAU = sqrt(gamma(nu)./(gamma(self.alpha)*(4*pi)*KAPPA.^(2*nu).*sigma.^2));
     107                        md.sampling.kappa = KAPPA.*ones(md.mesh.numberofvertices,1);
     108                        md.sampling.tau = TAU.*ones(md.mesh.numberofvertices,1);
    116109
    117110                end % }}}
     
    121114                        writejsdouble(fid,[modelname '.sampling.tau'],self.tau);
    122115                        writejsdouble(fid,[modelname '.sampling.beta'],self.beta);
    123                         writejsdouble(fid,[modelname '.sampling.phi'],self.beta);
     116                        writejsdouble(fid,[modelname '.sampling.phi'],self.phi);
    124117                        writejsdouble(fid,[modelname '.sampling.alpha'],self.alpha);
    125118                        writejsdouble(fid,[modelname '.sampling.robin'],self.robin);
  • issm/trunk/src/m/classes/solidearth.py

    r26744 r27035  
    11import numpy as np
    2 
    32from checkfield import checkfield
    43from fielddisplay import fielddisplay
     
    65from MatlabFuncs import *
    76from planetradius import planetradius
    8 from project3d import project3d
    97from rotational import rotational
    108from solidearthsettings import solidearthsettings
     
    2523
    2624    def __init__(self, *args):  # {{{
    27         self.settings           = solidearthsettings()
    28         self.external           = None
    29         self.lovenumbers        = lovenumbers()
    30         self.rotational         = rotational()
    31         self.planetradius       = planetradius('earth')
    32         self.requested_outputs  = []
    33         self.transitions        = []
    34         self.partitionice       = []
    35         self.partitionhydro     = []
    36         self.partitionocean     = []
     25        self.settings  = solidearthsettings()
     26        self.external  = None
     27        self.lovenumbers = lovenumbers()
     28        self.rotational = rotational()
     29        self.planetradius = planetradius('earth')
     30        self.requested_outputs = []
     31        self.transitions = []
     32        self.partitionice = []
     33        self.partitionhydro = []
     34        self.partitionocean = []
    3735
    3836        nargs = len(args)
     
    4442            raise Exception('solidearth constructor error message: zero or one argument only!')
    4543    # }}}
     44
    4645    def __repr__(self):  # {{{
    4746        s = '   solidearthinputs, forcings and settings:\n'
     
    5756        print(self.lovenumbers)
    5857        print(self.rotational)
    59         if len(self.external):
     58        try:
    6059            print(self.external)
     60        except TypeError:
     61            pass
    6162        return s
    6263    # }}}
     64
    6365    def setdefaultparameters(self, planet):  # {{{
    6466        # Output default
     
    7981        self.planetradius = planetradius(planet)
    8082    # }}}
     83
    8184    def checkconsistency(self, md, solution, analyses):  # {{{
    8285        if ('SealevelchangeAnalysis' not in analyses) or (solution == 'TransientSolution' and not md.transient.isslc):
     
    9497        return md
    9598    # }}}
     99
    96100    def defaultoutputs(self, md):  # {{{
    97101        return ['Sealevel']
    98102    # }}}
     103
    99104    def marshall(self, prefix, md, fid):  # {{{
    100105        WriteData(fid, prefix, 'object', self, 'fieldname', 'planetradius', 'format', 'Double')
     
    140145        WriteData(fid, prefix, 'data', outputs, 'name', 'md.solidearth.requested_outputs', 'format', 'StringArray')
    141146    # }}}
     147
    142148    def extrude(self, md):  # {{{
    143149        return self
  • issm/trunk/src/m/classes/solidearthsettings.py

    r26744 r27035  
    120120            if md.mesh.__class__.__name__ == 'mesh3dsurface':
    121121                if self.grdmodel == 2:
    122                     raise RuntimeException('model requires a 2D mesh to run gia Ivins computations (change mesh from mesh3dsurface to mesh2d)')
     122                    raise Exception('model requires a 2D mesh to run gia Ivins computations (change mesh from mesh3dsurface to mesh2d)')
    123123            else:
    124124                if self.grdmodel == 1:
    125                     raise RuntimeException('model requires a 3D surface mesh to run GRD computations (change mesh from mesh2d to mesh3dsurface)')
     125                    raise Exception('model requires a 3D surface mesh to run GRD computations (change mesh from mesh2d to mesh3dsurface)')
    126126            if self.sealevelloading and not self.grdocean:
    127                 raise RuntimeException('solidearthsettings checkconsistency error message: need grdocean on if sealevelloading flag is set')
     127                raise Exception('solidearthsettings checkconsistency error message: need grdocean on if sealevelloading flag is set')
    128128
    129129        if self.compute_bp_grd and not md.solidearth.settings.isgrd:
    130             raise RuntimeException('solidearthsettings checkconsistency error message; if bottom pressure grd patterns are requested, solidearth settings class should have isgrd flag on')
     130            raise Exception('solidearthsettings checkconsistency error message; if bottom pressure grd patterns are requested, solidearth settings class should have isgrd flag on')
    131131
    132132        return md
  • issm/trunk/src/m/classes/spatiallinearbasalforcings.m

    r25836 r27035  
    99                deepwater_melting_rate    = NaN;
    1010                deepwater_elevation       = NaN;
     11                upperwater_melting_rate   = NaN;
    1112                upperwater_elevation      = NaN;
     13                perturbation_melting_rate = NaN;
    1214                geothermalflux            = NaN;
    1315        end
     
    2527                                                self.deepwater_elevation=lb.deepwater_elevation*ones(nvertices,1);
    2628                                                self.deepwater_melting_rate=lb.deepwater_melting_rate*ones(nvertices,1);
     29                                                self.upperwater_melting_rate=lb.upperwater_melting_rate*ones(nvertices,1);
    2730                                                self.upperwater_elevation=lb.upperwater_elevation*ones(nvertices,1);
     31                                                self.perturbation_melting_rate=lb.perturbation_melting_rate*ones(nvertices,1);
    2832                                        else
    2933                                                self=structtoobj(spatiallinearbasalforcings(),varargin{1});
     
    3741                        self.deepwater_melting_rate=project3d(md,'vector',self.deepwater_melting_rate,'type','node','layer',1);
    3842                        self.deepwater_elevation=project3d(md,'vector',self.deepwater_elevation,'type','node','layer',1);
     43                        self.upperwater_melting_rate=project3d(md,'vector',self.upperwater_melting_rate,'type','node','layer',1);
    3944                        self.upperwater_elevation=project3d(md,'vector',self.upperwater_elevation,'type','node','layer',1);
    4045                        self.geothermalflux=project3d(md,'vector',self.geothermalflux,'type','node','layer',1); %bedrock only gets geothermal flux
     46                        self.perturbation_melting_rate=project3d(md,'vector',self.perturbation_melting_rate,'type','node','layer',1);
    4147                end % }}}
    4248                function self = initialize(self,md) % {{{
     
    5864                function md = checkconsistency(self,md,solution,analyses) % {{{
    5965
     66                        if numel(md.basalforcings.perturbation_melting_rate)>1
     67            md = checkfield(md,'fieldname','basalforcings.perturbation_melting_rate','NaN',1,'Inf',1,'timeseries',1);
     68         end
     69
    6070                        if ismember('MasstransportAnalysis',analyses) & ~(strcmp(solution,'TransientSolution') & md.transient.ismasstransport==0),
    6171                                md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1);
    6272                                md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','NaN',1,'Inf',1,'timeseries',1,'>=',0);
    6373                                md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','NaN',1,'Inf',1,'timeseries',1);
    64                                 md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','NaN',1,'Inf',1,'timeseries',1,'<',0);
     74                                md = checkfield(md,'fieldname','basalforcings.upperwater_melting_rate','NaN',1,'Inf',1,'timeseries',1,'>=',0);
     75                                md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','NaN',1,'Inf',1,'timeseries',1,'<=',0);
    6576                        end
    6677                        if ismember('BalancethicknessAnalysis',analyses),
     
    6980                                md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'numel',1);
    7081                                md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','numel',1);
     82                                md = checkfield(md,'fieldname','basalforcings.upperwater_melting_rate','>=',0,'numel',1);
    7183                                md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<=',0,'numel',1);
    7284                        end
     
    7688                                md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'numel',1);
    7789                                md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','numel',1);
    78                                 md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0,'numel',1);
     90                                md = checkfield(md,'fieldname','basalforcings.upperwater_melting_rate','>=',0,'numel',1);
     91                                md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<=',0,'numel',1);
    7992                                md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'Inf',1,'timeseries',1,'>=',0);
    8093                        end
     
    8699                        fielddisplay(self,'deepwater_melting_rate','basal melting rate (positive if melting applied for floating ice whith base < deepwater_elevation) [m/yr]');
    87100                        fielddisplay(self,'deepwater_elevation','elevation of ocean deepwater [m]');
     101                        fielddisplay(self,'upperwater_melting_rate','basal melting rate (positive if melting applied for floating ice whith base >= upperwater_elevation) [m/yr]');
    88102                        fielddisplay(self,'upperwater_elevation','elevation of ocean upperwater [m]');
     103                        fielddisplay(self,'perturbation_melting_rate','basal melting rate perturbation added to computed melting rate (positive if melting) [m/yr]');
    89104                        fielddisplay(self,'geothermalflux','geothermal heat flux [W/m^2]');
    90105
     
    94109                        yts=md.constants.yts;
    95110
    96                         floatingice_melting_rate=zeros(md.mesh.numberofvertices,1);
    97                         pos=find(md.geometry.base<=md.basalforcings.deepwater_elevation);
    98                         floatingice_melting_rate(pos)=md.basalforcings.deepwater_melting_rate(pos);
    99                         pos=find(md.geometry.base>md.basalforcings.deepwater_elevation & md.geometry.base<md.basalforcings.upperwater_elevation);
    100                         floatingice_melting_rate(pos)=md.basalforcings.deepwater_melting_rate(pos).*(md.geometry.base(pos)-md.basalforcings.upperwater_elevation(pos))./(md.basalforcings.deepwater_elevation(pos)-md.basalforcings.upperwater_elevation(pos));
    101111                        WriteData(fid,prefix,'name','md.basalforcings.model','data',6,'format','Integer');
    102                         WriteData(fid,prefix,'data',floatingice_melting_rate,'format','DoubleMat','name','md.basalforcings.floatingice_melting_rate','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
    103112                        WriteData(fid,prefix,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','name','md.basalforcings.groundedice_melting_rate','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
    104113                        WriteData(fid,prefix,'object',self,'fieldname','geothermalflux','name','md.basalforcings.geothermalflux','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
    105114                        WriteData(fid,prefix,'object',self,'fieldname','deepwater_melting_rate','format','DoubleMat','name','md.basalforcings.deepwater_melting_rate','scale',1./yts,'mattype',1);
    106115                        WriteData(fid,prefix,'object',self,'fieldname','deepwater_elevation','format','DoubleMat','name','md.basalforcings.deepwater_elevation','mattype',1);
     116                        WriteData(fid,prefix,'object',self,'fieldname','upperwater_melting_rate','format','DoubleMat','name','md.basalforcings.upperwater_melting_rate','scale',1./yts,'mattype',1);
    107117                        WriteData(fid,prefix,'object',self,'fieldname','upperwater_elevation','format','DoubleMat','name','md.basalforcings.upperwater_elevation','mattype',1);
     118                        WriteData(fid,prefix,'object',self,'fieldname','perturbation_melting_rate','format','DoubleMat','name','md.basalforcings.perturbation_melting_rate','scale',1./yts,'mattype',1);
    108119                end % }}}
    109120        end
  • issm/trunk/src/m/classes/spatiallinearbasalforcings.py

    r25836 r27035  
    2121            self.deepwater_melting_rate     = np.nan
    2222            self.deepwater_elevation        = np.nan
     23            self.upperwater_melting_rate    = np.nan
    2324            self.upperwater_elevation       = np.nan
    2425            self.geothermalflux             = np.nan
     26            self.perturbation_melting_rate  = np.nan
    2527
    2628            self.setdefaultparameters()
     
    3032                nvertices = len(lb.groundedice_melting_rate)
    3133                self.groundedice_melting_rate   = lb.groundedice_melting_rate
    32                 self.deepwater_melting_rate     = lb.geothermalflux
     34                self.geothermalflux             = lb.geothermalflux
    3335                self.deepwater_elevation        = lb.deepwater_elevation * np.ones((nvertices, ))
    34                 self.upperwater_elevation       = lb.deepwater_melting_rate * np.ones((nvertices, ))
    35                 self.geothermalflux             = lb.upperwater_elevation * np.ones((nvertices, ))
     36                self.deepwater_melting_rate     = lb.deepwater_melting_rate * np.ones((nvertices, ))
     37                self.upperwater_melting_rate    = lb.upperwater_melting_rate * np.ones((nvertices, ))
     38                self.upperwater_elevation       = lb.upperwater_elevation * np.ones((nvertices, ))
     39                self.perturbation_melting_rate  = lb.perturbation_melting_rate * np.ones((nvertices, ))
    3640            else:
    3741                # TODO: This has not been tested
     
    4650        s += '{}\n'.format(fielddisplay(self, 'deepwater_melting_rate', 'basal melting rate (positive if melting applied for floating ice whith base < deepwater_elevation) [m/yr]'))
    4751        s += '{}\n'.format(fielddisplay(self, 'deepwater_elevation', 'elevation of ocean deepwater [m]'))
     52        s += '{}\n'.format(fielddisplay(self, 'upperwater_melting_rate', 'basal melting rate (positive if melting applied for floating ice whith base >= upperwater_elevation) [m/yr]'))
    4853        s += '{}\n'.format(fielddisplay(self, 'upperwater_elevation', 'elevation of ocean upperwater [m]'))
     54        s += '{}\n'.format(fielddisplay(self, 'perturbation_melting_rate', 'basal melting rate perturbation added to computed melting rate (positive if melting) [m/yr]'))
    4955        s += '{}\n'.format(fielddisplay(self, 'geothermalflux', 'geothermal heat flux [W/m^2]'))
    5056        return s
     
    5561        self.deepwater_melting_rate = project3d(md, 'vector', self.deepwater_melting_rate, 'type', 'node', 'layer', 1)
    5662        self.deepwater_elevation = project3d(md, 'vector', self.deepwater_elevation, 'type', 'node', 'layer', 1)
     63        self.upperwater_melting_rate = project3d(md, 'vector', self.upperwater_melting_rate, 'type', 'node', 'layer', 1)
    5764        self.upperwater_elevation = project3d(md, 'vector', self.upperwater_elevation, 'type', 'node', 'layer', 1)
    5865        self.geothermalflux = project3d(md, 'vector', self.geothermalflux, 'type', 'node', 'layer', 1) # Bedrock only gets geothermal flux
     66        self.perturbation_melting_rate = project3d(md, 'vector', self.upperwater_melting_rate, 'type', 'node', 'layer', 1)
    5967        return self
    6068    #}}}
     
    7280
    7381    def checkconsistency(self, md, solution, analyses): #{{{
     82        if not np.all(np.isnan(self.perturbation_melting_rate)):
     83            md = checkfield(md, 'fieldname', 'basalforcings.perturbation_melting_rate', 'NaN', 1, 'Inf', 1, 'timeseries', 1)
    7484        if 'MasstransportAnalysis' in analyses and not solution == 'TransientSolution' and not md.transient.ismasstransport:
    7585            md = checkfield(md, 'fieldname', 'basalforcings.groundedice_melting_rate', 'NaN', 1, 'Inf', 1, 'timeseries', 1)
    7686            md = checkfield(md, 'fieldname', 'basalforcings.deepwater_melting_rate', 'NaN', 1, 'Inf', 1, 'timeseries', 1, '>=', 0)
    7787            md = checkfield(md, 'fieldname', 'basalforcings.deepwater_elevation', 'NaN', 1, 'Inf', 1, 'timeseries', 1)
     88            md = checkfield(md, 'fieldname', 'basalforcings.upperwater_melting_rate', 'NaN', 1, 'Inf', 1, 'timeseries', 1, '>=', 0)
    7889            md = checkfield(md, 'fieldname', 'basalforcings.upperwater_elevation', 'NaN', 1, 'Inf', 1, 'timeseries', 1, '<', 0)
    7990        if 'BalancethicknessAnalysis' in analyses:
     
    8293            md = checkfield(md, 'fieldname', 'basalforcings.deepwater_melting_rate', '>=', 0, 'numel', 1)
    8394            md = checkfield(md, 'fieldname', 'basalforcings.deepwater_elevation', '<', 'basalforcings.upperwater_elevation', 'numel', 1)
     95            md = checkfield(md, 'fieldname', 'basalforcings.upperwater_melting_rate', '>=', 0, 'numel', 1)
    8496            md = checkfield(md, 'fieldname', 'basalforcings.upperwater_elevation', '<=', 0, 'numel', 1)
    8597        if 'ThermalAnalysis' in analyses and not solution == 'TransientSolution' and not md.transient.isthermal:
     
    89101            md = checkfield(md, 'fieldname', 'basalforcings.deepwater_elevation', '<', 'basalforcings.upperwater_elevation', 'numel', 1)
    90102            md = checkfield(md, 'fieldname', 'basalforcings.upperwater_elevation', '<', 0, 'numel', 1)
     103            md = checkfield(md, 'fieldname', 'basalforcings.deepwater_melting_rate', '>=', 0, 'numel', 1)
    91104            md = checkfield(md, 'fieldname', 'basalforcings.geothermalflux', 'NaN', 1, 'Inf', 1, 'timeseries', 1, '>=', 0)
    92105        return md
     
    96109        yts = md.constants.yts
    97110
    98         floatingice_melting_rate = np.zeros((md.mesh.numberofvertices, ))
    99         pos = np.where(md.geometry.base <= md.basalforcings.deepwater_elevation)[0]
    100         floatingice_melting_rate[pos] = md.basalforcings.deepwater_melting_rate[pos]
    101         pos = np.where(np.logical_and.reduce(md.geometry.base > md.basalforcings.deepwater_elevation, md.geometry.base < md.basalforcings.upperwater_elevation))
    102         floatingice_melting_rate[pos] = md.basalforcings.deepwater_melting_rate[pos] * (md.geometry.base[pos] - md.basalforcings.upperwater_elevation[pos]) / (md.basalforcings.deepwater_elevation[pos] - md.basalforcings.upperwater_elevation[pos])
    103111        WriteData(fid, prefix, 'name', 'md.basalforcings.model', 'data', 6, 'format', 'Integer')
    104         WriteData(fid, prefix, 'data', floatingice_melting_rate, 'format', 'DoubleMat', 'name', 'md.basalforcings.floatingice_melting_rate', 'mattype', 1, 'scale', 1. / yts, 'timeserieslength', md.mesh.numberofvertices + 1, 'yts', md.constants.yts)
    105112        WriteData(fid, prefix, 'object', self, 'fieldname', 'groundedice_melting_rate', 'format', 'DoubleMat', 'name', 'md.basalforcings.groundedice_melting_rate', 'mattype', 1, 'scale', 1. / yts, 'timeserieslength', md.mesh.numberofvertices + 1,'yts', md.constants.yts)
    106113        WriteData(fid, prefix,'object', self, 'fieldname', 'geothermalflux', 'name', 'md.basalforcings.geothermalflux', 'format', 'DoubleMat', 'mattype', 1,'timeserieslength', md.mesh.numberofvertices + 1, 'yts', md.constants.yts)
    107114        WriteData(fid, prefix, 'object', self, 'fieldname', 'deepwater_melting_rate', 'format', 'DoubleMat', 'name', 'md.basalforcings.deepwater_melting_rate', 'scale', 1. / yts, 'mattype', 1)
    108115        WriteData(fid, prefix, 'object', self, 'fieldname', 'deepwater_elevation', 'format', 'DoubleMat', 'name', 'md.basalforcings.deepwater_elevation', 'mattype', 1)
     116        WriteData(fid, prefix, 'object', self, 'fieldname', 'upperwater_melting_rate', 'format', 'DoubleMat', 'name', 'md.basalforcings.upperwater_melting_rate', 'scale', 1. / yts, 'mattype', 1)
    109117        WriteData(fid, prefix, 'object', self, 'fieldname', 'upperwater_elevation', 'format', 'DoubleMat', 'name', 'md.basalforcings.upperwater_elevation', 'mattype', 1)
     118        WriteData(fid, prefix, 'object', self, 'fieldname', 'perturbation_melting_rate', 'format', 'DoubleMat', 'name', 'md.basalforcings.perturbation_melting_rate', 'scale', 1. / yts, 'mattype', 1)
    110119    #}}}
  • issm/trunk/src/m/classes/stochasticforcing.m

    r26744 r27035  
    1111                default_id                              = NaN;
    1212                covariance                              = NaN;
     13                stochastictimestep   = 0;
    1314                randomflag                              = 1;
    1415        end
     
    3536
    3637                        num_fields = numel(self.fields);
     38                        if(self.stochastictimestep==0)
     39                                md.stochasticforcing.stochastictimestep = md.timestepping.time_step; %by default: stochastictimestep set to ISSM time step
     40                        end
    3741
    3842                        %Check that covariance matrix is positive definite
     
    4852                        for field=self.fields
    4953                                %Checking agreement of classes
    50                                 if(contains(field,'SMB'))
     54                                if(contains(field,'SMBautoregression'))
    5155                                        mdname = structstoch.mdnames(find(strcmp(structstoch.fields,char(field))));
    5256                                        if~(isequal(class(md.smb),char(mdname)))
     
    5458                                        end
    5559                                end
     60                                if(contains(field,'SMBforcing'))
     61                                        mdname = structstoch.mdnames(find(strcmp(structstoch.fields,char(field))));
     62                                        if~(isequal(class(md.smb),char(mdname)))
     63                                                error('md.smb does not agree with stochasticforcing field %s', char(field));
     64                                        end
     65                                end
    5666                                if(contains(field,'FrontalForcings'))
    5767                                        mdname = structstoch.mdnames(find(strcmp(structstoch.fields,char(field))));
     
    6777                                end
    6878                                if(contains(field,'BasalforcingsFloatingice'))
     79                                        mdname = structstoch.mdnames(find(strcmp(structstoch.fields,char(field))));
     80                                        if~(isequal(class(md.basalforcings),char(mdname)))
     81                                                error('md.basalforcings does not agree with stochasticforcing field %s', char(field));
     82                                        end
     83                                end
     84                                if(contains(field,'BasalforcingsSpatialDeepwaterMeltingRate'))
     85                                        mdname = structstoch.mdnames(find(strcmp(structstoch.fields,char(field))));
     86                                        if~(isequal(class(md.basalforcings),char(mdname)))
     87                                                error('md.basalforcings does not agree with stochasticforcing field %s', char(field));
     88                                        end
     89                                end
     90                                if(contains(field,'BasalforcingsDeepwaterMeltingRateAutoregression'))
    6991                                        mdname = structstoch.mdnames(find(strcmp(structstoch.fields,char(field))));
    7092                                        if~(isequal(class(md.basalforcings),char(mdname)))
     
    85107            end
    86108                                %Checking for specific dimensions
    87                                 if ~(strcmp(field,'SMBautoregression') || strcmp(field,'FrontalForcingsRignotAutoregression'))
     109                                if ~(strcmp(field,'SMBautoregression') || strcmp(field,'FrontalForcingsRignotAutoregression') || strcmp(field,'BasalforcingsDeepwaterMeltingRateAutoregression'))
    88110                                        checkdefaults = true; %field with non-specific dimensionality
    89111                                end
    90112                        end
    91113
    92                         %Retrieve sum of all the field dimensionalities
    93                         size_tot        = self.defaultdimension*num_fields;
    94                         indSMBar        = -1; %about to check for index of SMBautoregression
    95                         indTFar = -1; %about to check for index of FrontalForcingsRignotAutoregression
     114                        %Retrieve all the field dimensionalities
     115                        dimensions = self.defaultdimension*ones(1,num_fields);
     116                        indSMBar   = -1; %about to check for index of SMBautoregression
     117                        indTFar   = -1; %about to check for index of FrontalForcingsRignotAutoregression
     118                        indBDWar          = -1; %about to check for index of BasalforcingsDeepwaterMeltingRateAutoregression
    96119                        if any(contains(self.fields,'SMBautoregression'))
    97                                 size_tot = size_tot-self.defaultdimension+md.smb.num_basins;
    98                                 indSMBar = find(contains(self.fields,'SMBautoregression')); %index of SMBar, now check for consistency with TFar timestep (08Nov2021)
     120                                indSMBar = find(contains(self.fields,'SMBautoregression')); %index of SMBar, now check for consistency with other ar timesteps
     121                                dimensions(indSMBar) = md.smb.num_basins;
     122                                if(md.smb.ar_timestep<self.stochastictimestep)
     123                                        error('SMBautoregression cannot have a timestep shorter than stochastictimestep');
     124                                end
    99125                        end
    100126                        if any(contains(self.fields,'FrontalForcingsRignotAutoregression'))
    101                                 size_tot        = size_tot-self.defaultdimension+md.frontalforcings.num_basins;
    102                                 indTFar = find(contains(self.fields,'FrontalForcingsRignotAutoregression')); %index of TFar, now check for consistency with SMBar timestep (08Nov2021)
    103                         end
     127                                indTFar = find(contains(self.fields,'FrontalForcingsRignotAutoregression')); %index of TFar, now check for consistency with other ar timesteps
     128                                dimensions(indTFar) = md.frontalforcings.num_basins;
     129                                if(md.frontalforcings.ar_timestep<self.stochastictimestep)
     130                                        error('FrontalForcingsRignotAutoregression cannot have a timestep shorter than stochastictimestep');
     131                                end
     132                        end
     133                        if any(contains(self.fields,'BasalforcingsDeepwaterMeltingRateAutoregression'))
     134                                indBDWar        = find(contains(self.fields,'BasalforcingsDeepwaterMeltingRateAutoregression')); %index of BDWar, now check for consistency with other ar timesteps
     135                                dimensions(indBDWar) = md.basalforcings.num_basins;
     136                                if(md.basalforcings.ar_timestep<self.stochastictimestep)
     137                                        error('BasalforcingsDeepwaterMeltingRateAutoregression cannot have a timestep shorter than stochastictimestep');
     138                                end
     139                        end
     140                        size_tot = sum(dimensions);
    104141
    105142                        if(indSMBar~=-1 && indTFar~=-1) %both autoregressive models are used: check autoregressive time step consistency
    106                                 if((md.smb.ar_timestep~=md.frontalforcings.ar_timestep) && any(self.covariance(1+sum(self.dimensions(1:indSMBar-1)):sum(self.dimensions(1:indSMBar)),1+sum(self.dimensions(1:indTFar-1)):sum(self.dimensions(1:indTFar))))~=0)
    107                                         error('SMBautoregression and FrontalForcingsRignotAutoregression have different ar_timestep and non-zero covariance');
    108                                 end
    109                         end
    110 
     143                                if(md.smb.ar_timestep~=md.frontalforcings.ar_timestep)
     144                                        crossentries = reshape(self.covariance(1+sum(dimensions(1:indSMBar-1)):sum(dimensions(1:indSMBar)),1+sum(dimensions(1:indTFar-1)):sum(dimensions(1:indTFar))),1,[]);
     145                                        if any(crossentries~=0)
     146                                                error('SMBautoregression and FrontalForcingsRignotAutoregression have different ar_timestep and non-zero covariance');
     147                                        end
     148                                end
     149                        end
     150                        if(indSMBar~=-1 && indBDWar~=-1) %both autoregressive models are used: check autoregressive time step consistency
     151                                if(md.smb.ar_timestep~=md.basalforcings.ar_timestep)
     152                                        crossentries = reshape(self.covariance(1+sum(dimensions(1:indSMBar-1)):sum(dimensions(1:indSMBar)),1+sum(dimensions(1:indBDWar-1)):sum(dimensions(1:indBDWar))),1,[]);
     153                                        if any(crossentries~=0)
     154                                                error('SMBautoregression and BasalforcingsDeepwaterMeltingRateAutoregression have different ar_timestep and non-zero covariance');
     155                                        end
     156                                end
     157                        end
     158                        if(indTFar~=-1 && indBDWar~=-1) %both autoregressive models are used: check autoregressive time step consistency
     159                                if(md.frontalforcings.ar_timestep~=md.basalforcings.ar_timestep)
     160                                        crossentries = reshape(self.covariance(1+sum(dimensions(1:indTFar-1)):sum(dimensions(1:indTFar)),1+sum(dimensions(1:indBDWar-1)):sum(dimensions(1:indBDWar))),1,[]);
     161                                        if any(crossentries~=0)
     162                                                error('FrontalForcingsRignotAutoregression and BasalforcingsDeepwaterMeltingRateAutoregression have different ar_timestep and non-zero covariance');
     163                                        end
     164                                end
     165                        end
    111166                        md = checkfield(md,'fieldname','stochasticforcing.isstochasticforcing','values',[0 1]);
    112167                        md = checkfield(md,'fieldname','stochasticforcing.fields','numel',num_fields,'cell',1,'values',supportedstochforcings());
    113168                        md = checkfield(md,'fieldname','stochasticforcing.covariance','NaN',1,'Inf',1,'size',[size_tot,size_tot]); %global covariance matrix
     169                        md = checkfield(md,'fieldname','stochasticforcing.stochastictimestep','NaN',1,'Inf',1,'>=',md.timestepping.time_step);
    114170                        md = checkfield(md,'fieldname','stochasticforcing.randomflag','numel',[1],'values',[0 1]);
    115171                        if(checkdefaults) %need to check the defaults
     
    121177                        disp(sprintf('   stochasticforcing parameters:'));
    122178                        fielddisplay(self,'isstochasticforcing','is stochasticity activated?');
    123                         fielddisplay(self,'fields','fields with stochasticity applied, ex: {''SMBautoregression''}, or {''FrontalForcingsRignotAutoregression''}');
     179                        fielddisplay(self,'fields','fields with stochasticity applied, ex: [{''SMBautoregression''}], or [{''SMBforcing''},{''DefaultCalving''}]');
    124180                        fielddisplay(self,'defaultdimension','dimensionality of the noise terms (does not apply to fields with their specific dimension)');
    125181                        fielddisplay(self,'default_id','id of each element for partitioning of the noise terms (does not apply to fields with their specific partition)');
    126182                        fielddisplay(self,'covariance','covariance matrix for within- and between-fields covariance (units must be squared field units)');
     183                        fielddisplay(self,'stochastictimestep','timestep at which new stochastic noise terms are generated (default: md.timestepping.time_step)');
    127184                        fielddisplay(self,'randomflag','whether to apply real randomness (true) or pseudo-randomness with fixed seed (false)');
    128185                        disp('Available fields:');
     
    140197                                return
    141198                        else
     199
     200                                if(self.stochastictimestep==0)
     201                                        disp('      stochasticforcing.stocahstictimestep not specified: set to md.timestepping.time_step');
     202                                        self.stochastictimestep = md.timestepping.time_step; %by default: stochastictimestep set to ISSM time step
     203                                end
    142204
    143205                                %Retrieve dimensionality of each field
     
    152214                                                dimensions(ind) = md.frontalforcings.num_basins;
    153215                                        end
     216                                        if(strcmp(field,'BasalforcingsDeepwaterMeltingRateAutoregression'))
     217                                                dimensions(ind) = md.basalforcings.num_basins;
     218                                        end
    154219                                        ind = ind+1;
    155220                                end
    156221
    157222                                %Scaling covariance matrix (scale column-by-column and row-by-row)
    158                                 scaledfields = {'DefaultCalving','FloatingMeltRate','SMBautoregression'}; %list of fields that need scaling *1/yts
     223                                scaledfields = {'BasalforcingsDeepwaterMeltingRateAutoregression','BasalforcingsSpatialDeepwaterMeltingRate','DefaultCalving','FloatingMeltRate','SMBautoregression','SMBforcing'}; %list of fields that need scaling *1/yts
    159224                                tempcovariance = self.covariance; %copy of covariance to avoid writing back in member variable
    160225                                for i=1:num_fields
     
    173238                                        self.default_id = zeros(md.mesh.numberofelements,1);
    174239                                end
     240
    175241                                WriteData(fid,prefix,'data',num_fields,'name','md.stochasticforcing.num_fields','format','Integer');
    176242                                WriteData(fid,prefix,'object',self,'fieldname','fields','format','StringArray');
     
    179245                                WriteData(fid,prefix,'object',self,'fieldname','defaultdimension','format','Integer');
    180246                                WriteData(fid,prefix,'data',tempcovariance,'name','md.stochasticforcing.covariance','format','DoubleMat');
     247                                WriteData(fid,prefix,'object',self,'fieldname','stochastictimestep','format','Double','scale',yts);
    181248                                WriteData(fid,prefix,'object',self,'fieldname','randomflag','format','Boolean');
    182249                        end
     
    195262        % supported and corresponding md names
    196263        structure.fields = {...
     264                'BasalforcingsDeepwaterMeltingRateAutoregression',...
     265                'BasalforcingsSpatialDeepwaterMeltingRate',...
    197266                'DefaultCalving',...
    198267                'FloatingMeltRate',...
    199268                'FrictionWaterPressure',...
    200269                'FrontalForcingsRignotAutoregression',...
    201                 'SMBautoregression'
     270                'SMBautoregression',...
     271                'SMBforcing'
    202272                };
    203273        structure.mdnames = {...
     274                'autoregressionlinearbasalforcings',...
     275                'spatiallinearbasalforcings',...
    204276                'calving',...
    205277                'basalforcings',...
    206278                'friction',...
    207279                'frontalforcingsrignotautoregression',...
    208                 'SMBautoregression'
     280                'SMBautoregression',...
     281                'SMBforcing'
    209282        };
    210283end % }}}
  • issm/trunk/src/m/classes/stochasticforcing.py

    r26744 r27035  
    1818        self.default_id = np.nan
    1919        self.covariance = np.nan
     20        self.stochastictimestep = 0
    2021        self.randomflag = 1
    2122
     
    2829        s = '   stochasticforcing parameters:\n'
    2930        s += '{}\n'.format(fielddisplay(self, 'isstochasticforcing', 'is stochasticity activated?'))
    30         s += '{}\n'.format(fielddisplay(self, 'fields', 'fields with stochasticity applied, ex: [\'SMBautoregression\'], or [\'FrontalForcingsRignotAutoregression\']'))
     31        s += '{}\n'.format(fielddisplay(self, 'fields', 'fields with stochasticity applied, ex: [\'SMBautoregression\'], or [\'SMBforcing\',\'DefaultCalving\']'))
    3132        s += '{}\n'.format(fielddisplay(self, 'defaultdimension', 'dimensionality of the noise terms (does not apply to fields with their specific dimension)'))
    3233        s += '{}\n'.format(fielddisplay(self, 'default_id', 'id of each element for partitioning of the noise terms (does not apply to fields with their specific partition)'))
    3334        s += '{}\n'.format(fielddisplay(self, 'covariance', 'covariance matrix for within- and between-fields covariance (units must be squared field units)'))
     35        s += '{}\n'.format(fielddisplay(self, 'stochastictimestep', 'timestep at which new stochastic noise terms are generated (default: md.timestepping.time_step)'))
    3436        s += '{}\n'.format(fielddisplay(self, 'randomflag', 'whether to apply real randomness (true) or pseudo-randomness with fixed seed (false)'))
    3537        s += 'Available fields:\n'
     38        s += '   BasalforcingsSpatialDeepwaterMeltingRate\n'
    3639        s += '   DefaultCalving\n'
    3740        s += '   FloatingMeltRate\n'
     41        s += '   FrictionWaterPressure\n'
     42        s += '   FrontalForcingsRignotAutoregression (thermal forcing)\n'
    3843        s += '   SMBautoregression\n'
    39         s += '   FrontalForcingsRignotAutoregression (thermal forcing)\n'
     44        s += '   SMBforcing\n'
    4045        return s
    4146    #}}}
     
    4348    def setdefaultparameters(self):  # {{{
    4449        # Type of stabilization used
    45         self.isstochasticforcing = 0 # stochasticforcing is turned off by default
    46         self.fields = [] # Need to initialize to list to avoid "RuntimeError: object of type 'float' has no len()" on import of class
    47         self.randomflag = 1 # true randomness is implemented by default
     50        self.isstochasticforcing = 0  # stochasticforcing is turned off by default
     51        self.fields = []  # Need to initialize to list to avoid "RuntimeError: object of type 'float' has no len()" on import of class
     52        self.randomflag = 1  # true randomness is implemented by default
    4853        return self
    4954    #}}}
     
    5560
    5661        num_fields = len(self.fields)
     62        if(self.stochastictimestep==0):
     63            md.stochasticforcing.stochastictimestep = md.timestepping.time_step #by default: stochastictimestep set to ISSM time step
     64            print('      stochasticforcing.stocahstictimestep not specified: set to md.timestepping.time_step')
    5765
    5866        # Check that covariance matrix is positive definite (this is done internally by linalg)
     
    6371
    6472        # Check that all fields agree with the corresponding md class and if any field needs the default params
    65         checkdefaults = False # Need to check defaults only if one of the fields does not have its own dimensionality
     73        checkdefaults = False  # Need to check defaults only if one of the fields does not have its own dimensionality
    6674        structstoch = self.structstochforcing()
    6775        for field in self.fields:
    6876            # Checking agreement of classes
    69             if 'SMB' in field:
     77            if 'SMBautoregression' in field:
     78                mdname = structstoch[field]
     79                if (type(md.smb).__name__ != mdname):
     80                    raise TypeError('md.smb does not agree with stochasticforcing field {}'.format(field))
     81            if 'SMBforcing' in field:
    7082                mdname = structstoch[field]
    7183                if (type(md.smb).__name__ != mdname):
     
    8395                if (type(md.basalforcings).__name__ != mdname):
    8496                    raise TypeError('md.basalforcings does not agree with stochasticforcing field {}'.format(field))
     97            if 'BasalforcingsSpatialDeepwaterMeltingRate' in field:
     98                mdname = structstoch[field]
     99                if (type(md.basalforcings).__name__ != mdname):
     100                    raise TypeError('md.basalforcings does not agree with stochasticforcing field {}'.format(field))
     101            if 'BasalforcingsDeepwaterMeltingRateAutoregression' in field:
     102                mdname = structstoch[field]
     103                if (type(md.basalforcings).__name__ != mdname):
     104                    raise TypeError('md.basalforcings does not agree with stochasticforcing field {}'.format(field))
    85105            if 'WaterPressure' in field:
    86106                mdname = structstoch[field]
    87107                if (type(md.friction).__name__ != mdname):
    88108                    raise TypeError('stochasticforcing field {} is only implemented for default friction'.format(field))
    89                 if (md.friction.coupling!=0 and md.friction.coupling!=1 and md.friction.coupling!=2):
     109                if md.friction.coupling not in[0, 1, 2]:
    90110                    raise TypeError('stochasticforcing field {} is only implemented for cases md.friction.coupling 0 or 1 or 2'.format(field))
    91                 if (np.any(md.friction.q==0)):
    92                         raise TypeError('stochasticforcing field {} requires non-zero q exponent'.format(field))
     111                if (np.any(md.friction.q == 0)):
     112                    raise TypeError('stochasticforcing field {} requires non-zero q exponent'.format(field))
    93113
    94114            # Checking for specific dimensions
    95             if not (field == 'SMBautoregression' or field == 'FrontalForcingsRignotAutoregression'):
    96                 checkdefaults = True # field with non-specific dimensionality
     115            if field not in['SMBautoregression', 'FrontalForcingsRignotAutoregression','BasalforcingsDeepwaterMeltingRateAutoregression']:
     116                checkdefaults = True  # field with non-specific dimensionality
    97117
    98118        # Retrieve sum of all the field dimensionalities
    99         size_tot = self.defaultdimension * num_fields
    100         indSMBar = -1 # About to check for index of SMBautoregression
    101         indTFar = -1 # About to check for index of FrontalForcingsRignotAutoregression
     119        dimensions = self.defaultdimension*np.ones((num_fields))
     120        indSMBar   = -1  # About to check for index of SMBautoregression
     121        indTFar    = -1  # About to check for index of FrontalForcingsRignotAutoregression
     122        indBDWar   = -1  # About to check for index of BasalforcingsDeepwaterMeltingRateAutoregression
    102123        if ('SMBautoregression' in self.fields):
    103             size_tot = size_tot - self.defaultdimension + md.smb.num_basins
    104             indSMBar = self.fields.index('SMBautoregression') # Index of SMBar, now check for consistency with TFar timestep (08Nov2021)
     124            indSMBar = self.fields.index('SMBautoregression')  # Index of SMBar, now check for consistency with other timesteps
     125            dimensions[indSMBar] = md.smb.num_basins
     126            if(md.smb.ar_timestep<self.stochastictimestep):
     127                raise TypeError('SMBautoregression cannot have a timestep shorter than stochastictimestep')
    105128        if ('FrontalForcingsRignotAutoregression' in self.fields):
    106             size_tot = size_tot - self.defaultdimension + md.frontalforcings.num_basins
    107             indTFar = self.fields.index('FrontalForcingsRignotAutoregression') # Index of TFar, now check for consistency with SMBar timestep (08Nov2021)
    108         if (indSMBar != -1 and indTFar != -1): # Both autoregressive models are used: check autoregressive time step consistency
    109             covsum = self.covariance[np.sum(self.defaultdimensions[0:indSMBar]).astype(int):np.sum(self.defaultdimensions[0:indSMBar + 1]).astype(int), np.sum(self.defaultdimensions[0:indTFar]).astype(int):np.sum(self.defaultdimensions[0:indTFar + 1]).astype(int)]
     129            indTFar = self.fields.index('FrontalForcingsRignotAutoregression')  # Index of TFar, now check for consistency with other timesteps
     130            dimensions[indTFar] = md.frontalforcings.num_basins
     131            if(md.frontalforcings.ar_timestep<self.stochastictimestep):
     132                raise TypeError('FrontalForcingsRignotAutoregression cannot have a timestep shorter than stochastictimestep')
     133        if ('BasalforcingsDeepwaterMeltingRateAutoregression' in self.fields):
     134            indBDWar = self.fields.index('BasalforcingsDeepwaterMeltingRateAutoregression')  # Index of BDWar, now check for consistency with other timesteps
     135            dimensions[indTFar] = md.basalforcings.num_basins
     136            if(md.basalforcings.ar_timestep<self.stochastictimestep):
     137                raise TypeError('BasalforcingsDeepwaterMeltingRateAutoregression cannot have a timestep shorter than stochastictimestep')
     138        size_tot = np.sum(dimensions)
     139
     140        if (indSMBar != -1 and indTFar != -1):  # Both autoregressive models are used: check autoregressive time step consistency
     141            covsum = self.covariance[np.sum(dimensions[0:indSMBar]).astype(int):np.sum(dimensions[0:indSMBar + 1]).astype(int), np.sum(dimensions[0:indTFar]).astype(int):np.sum(dimensions[0:indTFar + 1]).astype(int)]
    110142            if((md.smb.ar_timestep != md.frontalforcings.ar_timestep) and np.any(covsum != 0)):
    111143                raise IOError('SMBautoregression and FrontalForcingsRignotAutoregression have different ar_timestep and non-zero covariance')
     144        if (indSMBar != -1 and indBDWar != -1):  # Both autoregressive models are used: check autoregressive time step consistency
     145            covsum = self.covariance[np.sum(dimensions[0:indSMBar]).astype(int):np.sum(dimensions[0:indSMBar + 1]).astype(int), np.sum(dimensions[0:indBDWar]).astype(int):np.sum(dimensions[0:indBDWar + 1]).astype(int)]
     146            if((md.smb.ar_timestep != md.basalforcings.ar_timestep) and np.any(covsum != 0)):
     147                raise IOError('SMBautoregression and BasalforcingsDeepwaterMeltingRateAutoregression have different ar_timestep and non-zero covariance')
     148        if (indTFar != -1 and indBDWar != -1):  # Both autoregressive models are used: check autoregressive time step consistency
     149            covsum = self.covariance[np.sum(dimensions[0:indTFar]).astype(int):np.sum(dimensions[0:indTFar + 1]).astype(int), np.sum(dimensions[0:indBDWar]).astype(int):np.sum(dimensions[0:indBDWar + 1]).astype(int)]
     150            if((md.frontalforcings.ar_timestep != md.basalforcings.ar_timestep) and np.any(covsum != 0)):
     151                raise IOError('FrontalForcingsRignotAutoregression and BasalforcingsDeepwaterMeltingRateAutoregression have different ar_timestep and non-zero covariance')
    112152
    113153        md = checkfield(md, 'fieldname', 'stochasticforcing.isstochasticforcing', 'values', [0, 1])
    114154        md = checkfield(md, 'fieldname', 'stochasticforcing.fields', 'numel', num_fields, 'cell', 1, 'values', self.supportedstochforcings())
    115155        md = checkfield(md, 'fieldname', 'stochasticforcing.covariance', 'NaN', 1, 'Inf', 1, 'size', [size_tot, size_tot])  # global covariance matrix
     156        md = checkfield(md, 'fieldname', 'stochasticforcing.stochastictimestep', 'NaN', 1,'Inf', 1, '>=', md.timestepping.time_step)
    116157        md = checkfield(md, 'fieldname', 'stochasticforcing.randomflag', 'numel', [1], 'values', [0, 1])
    117158        if (checkdefaults):
    118159            md = checkfield(md, 'fieldname', 'stochasticforcing.defaultdimension', 'numel', 1, 'NaN', 1, 'Inf', 1, '>', 0)
    119             md = checkfield(md, 'fieldname', 'stochasticforcing.default_id','Inf',1,'NaN',1,'>=',0,'<=',self.defaultdimension,'size', [md.mesh.numberofelements])
     160            md = checkfield(md, 'fieldname', 'stochasticforcing.default_id', 'Inf', 1, 'NaN', 1, '>=', 0, '<=', self.defaultdimension, 'size', [md.mesh.numberofelements])
    120161        return md
    121162    # }}}
     
    128169    def marshall(self, prefix, md, fid):  # {{{
    129170        yts = md.constants.yts
    130         num_fields = len(self.fields)
    131171
    132172        WriteData(fid, prefix, 'object', self, 'fieldname', 'isstochasticforcing', 'format', 'Boolean')
    133173        if not self.isstochasticforcing:
    134174            return md
     175
    135176        else:
     177            num_fields = len(self.fields)
     178            if(self.stochastictimestep==0):
     179                md.stochasticforcing.stochastictimestep = md.timestepping.time_step #by default: stochastictimestep set to ISSM time step
    136180            # Retrieve dimensionality of each field
    137             dimensions = self.defaultdimension * np.ones((num_fields,))
     181            dimensions = self.defaultdimension * np.ones((num_fields))
    138182            for ind, field in enumerate(self.fields):
    139183                # Checking for specific dimensions
     
    142186                if (field == 'FrontalForcingsRignotAutoregression'):
    143187                    dimensions[ind] = md.frontalforcings.num_basins
     188                if (field == 'BasalforcingsDeepwaterMeltingRateAutoregression'):
     189                    dimensions[ind] = md.basalforcings.num_basins
    144190
    145191            # Scaling covariance matrix (scale column-by-column and row-by-row)
    146             scaledfields = ['DefaultCalving','FloatingMeltRate','SMBautoregression'] # list of fields that need scaling * 1/yts
     192            scaledfields = ['BasalforcingsDeepwaterMeltingRateAutoregression','BasalforcingsSpatialDeepwaterMeltingRate','DefaultCalving', 'FloatingMeltRate', 'SMBautoregression', 'SMBforcing'] # list of fields that need scaling * 1/yts
    147193            tempcovariance = np.copy(self.covariance)
    148194            for i in range(num_fields):
     
    157203                self.default_id = np.zeros(md.mesh.numberofelements)
    158204            # Reshape dimensions as column array for marshalling
    159             dimensions = dimensions.reshape(1,len(dimensions))
     205            dimensions = dimensions.reshape(1, len(dimensions))
    160206
    161207            WriteData(fid, prefix, 'data', num_fields, 'name', 'md.stochasticforcing.num_fields', 'format', 'Integer')
    162208            WriteData(fid, prefix, 'object', self, 'fieldname', 'fields', 'format', 'StringArray')
    163             WriteData(fid, prefix, 'data', dimensions, 'name', 'md.stochasticforcing.dimensions', 'format', 'IntMat','mattype',2)
    164             WriteData(fid, prefix, 'object', self, 'fieldname', 'default_id', 'format', 'IntMat', 'mattype', 2)  #12Nov2021 make sure this is zero-indexed!
     209            WriteData(fid, prefix, 'data', dimensions, 'name', 'md.stochasticforcing.dimensions', 'format', 'IntMat', 'mattype', 2)
     210            WriteData(fid, prefix, 'object', self, 'fieldname', 'default_id', 'data', self.default_id - 1, 'format', 'IntMat', 'mattype', 2)  #12Nov2021 make sure this is zero-indexed!
    165211            WriteData(fid, prefix, 'object', self, 'fieldname', 'defaultdimension', 'format', 'Integer')
    166212            WriteData(fid, prefix, 'data', tempcovariance, 'name', 'md.stochasticforcing.covariance', 'format', 'DoubleMat')
     213            WriteData(fid, prefix, 'object', self, 'fieldname', 'stochastictimestep', 'format', 'Double', 'scale', yts)
    167214            WriteData(fid, prefix, 'object', self, 'fieldname', 'randomflag', 'format', 'Boolean')
    168215    # }}}
     
    180227           supported and corresponding md names
    181228        """
    182         structure = {'DefaultCalving': 'calving',
     229        structure = {'BasalforcingsDeepwaterMeltingRateAutoregression': 'autoregressionlinearbasalforcings',
     230                     'BasalforcingsSpatialDeepwaterMeltingRate': 'spatiallinearbasalforcings',
     231                     'DefaultCalving': 'calving',
    183232                     'FloatingMeltRate': 'basalforcings',
    184233                     'FrictionWaterPressure': 'friction',
    185234                     'FrontalForcingsRignotAutoregression': 'frontalforcingsrignotautoregression',
    186                      'SMBautoregression': 'SMBautoregression'}
     235                     'SMBautoregression': 'SMBautoregression',
     236                     'SMBforcing': 'SMBforcing'}
    187237        return structure
    188238    # }}}
  • issm/trunk/src/m/classes/stressbalance.m

    r26744 r27035  
    3636                        self.loadingforce=project3d(md,'vector',self.loadingforce,'type','node');
    3737
    38                         % for MLHO
    39                         if md.flowequation.isMLHO
     38                        % for MOLHO
     39                        if md.flowequation.isMOLHO
    4040                                self.spcvx_base=project3d(md,'vector',self.spcvx_base,'type','node');
    4141                                self.spcvy_base=project3d(md,'vector',self.spcvy_base,'type','node');
     
    134134                                md = checkfield(md,'fieldname','stressbalance.FSreconditioning','>',0);
    135135                        end
    136                         % CHECK THIS ONLY WORKS FOR MLHO
    137                         if md.flowequation.isMLHO
     136                        % CHECK THIS ONLY WORKS FOR MOLHO
     137                        if md.flowequation.isMOLHO
    138138                                md = checkfield(md,'fieldname','stressbalance.spcvx_base','Inf',1,'timeseries',1);
    139139                                md = checkfield(md,'fieldname','stressbalance.spcvy_base','Inf',1,'timeseries',1);
     
    169169                        fielddisplay(self,'spcvz','z-axis velocity constraint (NaN means no constraint) [m/yr]');
    170170
    171                         disp(sprintf('\n      %s','MLHO boundary conditions:'));
     171                        disp(sprintf('\n      %s','MOLHO boundary conditions:'));
    172172                        fielddisplay(self,'spcvx_base','x-axis basal velocity constraint (NaN means no constraint) [m/yr]');
    173173                        fielddisplay(self,'spcvy_base','y-axis basal velocity constraint (NaN means no constraint) [m/yr]');
     
    226226                        end
    227227                        WriteData(fid,prefix,'data',outputs,'name','md.stressbalance.requested_outputs','format','StringArray');
    228                         % for MLHO
    229                         if (md.flowequation.isMLHO)
     228                        % for MOLHO
     229                        if (md.flowequation.isMOLHO)
    230230                                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','spcvx_base','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
    231231                                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','spcvy_base','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
  • issm/trunk/src/m/classes/stressbalance.py

    r26744 r27035  
    5959        s += '{}\n'.format(fielddisplay(self, 'spcvz', 'z-axis velocity constraint (NaN means no constraint) [m / yr]'))
    6060        s += '{}\n'.format(fielddisplay(self, 'icefront', 'segments on ice front list (last column 0: Air, 1: Water, 2: Ice'))
    61         s += '      MLHO boundary conditions:\n'
     61        s += '      MOLHO boundary conditions:\n'
    6262        s += '{}\n'.format(fielddisplay(self, 'spcvx_base', 'x-axis basal velocity constraint (NaN means no constraint) [m / yr]'))
    6363        s += '{}\n'.format(fielddisplay(self, 'spcvy_base', 'y-axis basal velocity constraint (NaN means no constraint) [m / yr]'))
     
    8686        self.loadingforce = project3d(md, 'vector', self.loadingforce, 'type', 'node')
    8787
    88         if md.flowequation.isMLHO:
     88        if md.flowequation.isMOLHO:
    8989            self.spcvx_base = project3d(md, 'vector', self.spcvx_base, 'type', 'node')
    9090            self.spcvy_base = project3d(md, 'vector', self.spcvy_base, 'type', 'node')
     
    176176            if np.any(np.logical_not(np.isnan(md.stressbalance.referential[pos, :]))):
    177177                md.checkmessage("no referential should be specified for basal vertices of grounded ice")
    178         if md.flowequation.isMLHO:
     178        if md.flowequation.isMOLHO:
    179179            md = checkfield(md, 'fieldname', 'stressbalance.spcvx_base', 'Inf', 1, 'timeseries', 1)
    180180            md = checkfield(md, 'fieldname', 'stressbalance.spcvy_base', 'Inf', 1, 'timeseries', 1)
     
    215215            outputs = outputscopy
    216216        WriteData(fid, prefix, 'data', outputs, 'name', 'md.stressbalance.requested_outputs', 'format', 'StringArray')
    217         # MLHO
    218         if md.flowequation.isMLHO:
     217        # MOLHO
     218        if md.flowequation.isMOLHO:
    219219            WriteData(fid, prefix, 'object', self, 'class', 'stressbalance', 'fieldname', 'spcvx_base', 'format', 'DoubleMat', 'mattype', 1, 'scale', 1. / yts, 'timeserieslength', md.mesh.numberofvertices + 1, 'yts', yts)
    220220            WriteData(fid, prefix, 'object', self, 'class', 'stressbalance', 'fieldname', 'spcvy_base', 'format', 'DoubleMat', 'mattype', 1, 'scale', 1. / yts, 'timeserieslength', md.mesh.numberofvertices + 1, 'yts', yts)
  • issm/trunk/src/m/classes/taoinversion.py

    r25836 r27035  
    11import numpy as np
    2 
    32from checkfield import checkfield
    43from IssmConfig import IssmConfig
    54from marshallcostfunctions import marshallcostfunctions
     5from fielddisplay import fielddisplay
    66from project3d import project3d
    77from supportedcontrols import *
     
    4545    def __repr__(self):
    4646        s = '   taoinversion parameters:\n'
    47         s += '{}'.format(fieldstring(self, 'iscontrol', 'is inversion activated?'))
    48         s += '{}'.format(fieldstring(self, 'mantle_viscosity', 'mantle viscosity constraints (NaN means no constraint) (Pa s)'))
    49         s += '{}'.format(fieldstring(self, 'lithosphere_thickness', 'lithosphere thickness constraints (NaN means no constraint) (m)'))
    50         s += '{}'.format(fieldstring(self, 'cross_section_shape', "1: square-edged, 2: elliptical - edged surface"))
    51         s += '{}'.format(fieldstring(self, 'incomplete_adjoint', '1: linear viscosity, 0: non - linear viscosity'))
    52         s += '{}'.format(fieldstring(self, 'control_parameters', 'ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}'))
    53         s += '{}'.format(fieldstring(self, 'maxsteps', 'maximum number of iterations (gradient computation)'))
    54         s += '{}'.format(fieldstring(self, 'maxiter', 'maximum number of Function evaluation (forward run)'))
    55         s += '{}'.format(fieldstring(self, 'fatol', 'convergence criterion: f(X) - f(X * ) (X: current iteration, X * : "true" solution, f: cost function)'))
    56         s += '{}'.format(fieldstring(self, 'frtol', 'convergence criterion: |f(X) - f(X * )| / |f(X * )|'))
    57         s += '{}'.format(fieldstring(self, 'gatol', 'convergence criterion: ||g(X)|| (g: gradient of the cost function)'))
    58         s += '{}'.format(fieldstring(self, 'grtol', 'convergence criterion: ||g(X)|| / |f(X)|'))
    59         s += '{}'.format(fieldstring(self, 'gttol', 'convergence criterion: ||g(X)|| / ||g(X0)|| (g(X0): gradient at initial guess X0)'))
    60         s += '{}'.format(fieldstring(self, 'algorithm', 'minimization algorithm: ''tao_blmvm'', ''tao_cg'', ''tao_lmvm'''))
    61         s += '{}'.format(fieldstring(self, 'cost_functions', 'indicate the type of response for each optimization step'))
    62         s += '{}'.format(fieldstring(self, 'cost_functions_coefficients', 'cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter'))
    63         s += '{}'.format(fieldstring(self, 'min_parameters', 'absolute minimum acceptable value of the inversed parameter on each vertex'))
    64         s += '{}'.format(fieldstring(self, 'max_parameters', 'absolute maximum acceptable value of the inversed parameter on each vertex'))
    65         s += '{}'.format(fieldstring(self, 'vx_obs', 'observed velocity x component [m / yr]'))
    66         s += '{}'.format(fieldstring(self, 'vy_obs', 'observed velocity y component [m / yr]'))
    67         s += '{}'.format(fieldstring(self, 'vel_obs', 'observed velocity magnitude [m / yr]'))
    68         s += '{}'.format(fieldstring(self, 'thickness_obs', 'observed thickness [m]'))
    69         s += '{}'.format(fieldstring(self, 'surface_obs', 'observed surface elevation [m]'))
    70         s += '{}'.format('Available cost functions:')
    71         s += '{}'.format('   101: SurfaceAbsVelMisfit')
    72         s += '{}'.format('   102: SurfaceRelVelMisfit')
    73         s += '{}'.format('   103: SurfaceLogVelMisfit')
    74         s += '{}'.format('   104: SurfaceLogVxVyMisfit')
    75         s += '{}'.format('   105: SurfaceAverageVelMisfit')
    76         s += '{}'.format('   201: ThicknessAbsMisfit')
    77         s += '{}'.format('   501: DragCoefficientAbsGradient')
    78         s += '{}'.format('   502: RheologyBbarAbsGradient')
    79         s += '{}'.format('   503: ThicknessAbsGradient')
     47        s += '{}\n'.format(fielddisplay(self, 'iscontrol', 'is inversion activated?'))
     48        # s += '{}\n'.format(fielddisplay(self, 'mantle_viscosity', 'mantle viscosity constraints (NaN means no constraint) (Pa s)'))
     49        # s += '{}\n'.format(fielddisplay(self, 'lithosphere_thickness', 'lithosphere thickness constraints (NaN means no constraint) (m)'))
     50        # s += '{}\n'.format(fielddisplay(self, 'cross_section_shape', "1: square-edged, 2: elliptical - edged surface"))
     51        s += '{}\n'.format(fielddisplay(self, 'incomplete_adjoint', '1: linear viscosity, 0: non - linear viscosity'))
     52        s += '{}\n'.format(fielddisplay(self, 'control_parameters', 'ex: {''FrictionCoefficient''}, or {''MaterialsRheologyBbar''}'))
     53        s += '{}\n'.format(fielddisplay(self, 'maxsteps', 'maximum number of iterations (gradient computation)'))
     54        s += '{}\n'.format(fielddisplay(self, 'maxiter', 'maximum number of Function evaluation (forward run)'))
     55        s += '{}\n'.format(fielddisplay(self, 'fatol', 'convergence criterion: f(X) - f(X * ) (X: current iteration, X * : "true" solution, f: cost function)'))
     56        s += '{}\n'.format(fielddisplay(self, 'frtol', 'convergence criterion: |f(X) - f(X * )| / |f(X * )|'))
     57        s += '{}\n'.format(fielddisplay(self, 'gatol', 'convergence criterion: ||g(X)|| (g: gradient of the cost function)'))
     58        s += '{}\n'.format(fielddisplay(self, 'grtol', 'convergence criterion: ||g(X)|| / |f(X)|'))
     59        s += '{}\n'.format(fielddisplay(self, 'gttol', 'convergence criterion: ||g(X)|| / ||g(X0)|| (g(X0): gradient at initial guess X0)'))
     60        s += '{}\n'.format(fielddisplay(self, 'algorithm', 'minimization algorithm: ''tao_blmvm'', ''tao_cg'', ''tao_lmvm'''))
     61        s += '{}\n'.format(fielddisplay(self, 'cost_functions', 'indicate the type of response for each optimization step'))
     62        s += '{}\n'.format(fielddisplay(self, 'cost_functions_coefficients', 'cost_functions_coefficients applied to the misfit of each vertex and for each control_parameter'))
     63        s += '{}\n'.format(fielddisplay(self, 'min_parameters', 'absolute minimum acceptable value of the inversed parameter on each vertex'))
     64        s += '{}\n'.format(fielddisplay(self, 'max_parameters', 'absolute maximum acceptable value of the inversed parameter on each vertex'))
     65        s += '{}\n'.format(fielddisplay(self, 'vx_obs', 'observed velocity x component [m / yr]'))
     66        s += '{}\n'.format(fielddisplay(self, 'vy_obs', 'observed velocity y component [m / yr]'))
     67        s += '{}\n'.format(fielddisplay(self, 'vel_obs', 'observed velocity magnitude [m / yr]'))
     68        s += '{}\n'.format(fielddisplay(self, 'thickness_obs', 'observed thickness [m]'))
     69        s += '{}\n'.format(fielddisplay(self, 'surface_obs', 'observed surface elevation [m]'))
     70        s += '{}\n'.format('Available cost functions:')
     71        s += '{}\n'.format('   101: SurfaceAbsVelMisfit')
     72        s += '{}\n'.format('   102: SurfaceRelVelMisfit')
     73        s += '{}\n'.format('   103: SurfaceLogVelMisfit')
     74        s += '{}\n'.format('   104: SurfaceLogVxVyMisfit')
     75        s += '{}\n'.format('   105: SurfaceAverageVelMisfit')
     76        s += '{}\n'.format('   201: ThicknessAbsMisfit')
     77        s += '{}\n'.format('   501: DragCoefficientAbsGradient')
     78        s += '{}\n'.format('   502: RheologyBbarAbsGradient')
     79        s += '{}\n'.format('   503: ThicknessAbsGradient')
    8080        return s
    8181
  • issm/trunk/src/m/consistency/checkfield.py

    r26744 r27035  
    114114        else:
    115115            if len(np.shape(field)) < len(fieldsize):
    116                 md = md.checkmessage(options.getfieldvalue('message', "field {} has size {} but should be size {}".format(fieldname, np.shape(field), fieldsize)))
     116                if fieldsize[-1] > 1:
     117                    md = md.checkmessage(options.getfieldvalue('message', "field {} has size {} but should be size {}".format(fieldname, np.shape(field), fieldsize)))
     118                else:
     119                    #The last dimension is one that follows matlab 2D array regulation but usually not what we do in python, we allow the difference in shape only if the number of element is equal
     120                    if np.prod(np.shape(field)) != np.prod(fieldsize):
     121                        md = md.checkmessage(options.getfieldvalue('message', "field {} has size {} but should be size {}".format(fieldname, np.shape(field), fieldsize)))
    117122            else:
    118123                for i in range(np.size(fieldsize)):
     
    153158                md = md.checkmessage(options.getfieldvalue('message', "field '{}' value should be '{}'".format(fieldname, fieldvalues[0])))
    154159            elif len(fieldvalues) == 2:
    155                 md = md.checkmessage(options.getfieldvalue('message', "field '{}' values should be '{}' '{}' or '{}'".format(fieldname, fieldvalues[0], fieldvalues[1])))
     160                md = md.checkmessage(options.getfieldvalue('message', "field '{}' values should be '{}' or '{}'".format(fieldname, fieldvalues[0], fieldvalues[1])))
    156161            else:
    157162                md = md.checkmessage(options.getfieldvalue('message', "field '{}' should have values in {}".format(fieldname, fieldvalues)))
  • issm/trunk/src/m/consistency/comparemodels.m

    r25836 r27035  
    2727        if any(size(field1)~=size(field2)),
    2828                disp([fieldname ' do not have the same size']);
    29         elseif isnumeric(field1),
     29        elseif isnumeric(field1)
    3030                if numel(field1)==1 & isnan(field1) & isnan(field2),
    3131                        %Do not do anything
    32                 elseif any(field1~=field2),
     32                elseif any(field1(:)~=field2(:))
    3333                        %Deal with NaN...
    3434                        pos1=find(isnan(field1));
     
    3636                        if numel(pos1)==numel(pos2) & all(pos1==pos2),
    3737                                field1(pos1)=0; field2(pos2)=0;
    38                                 if any(field1~=field2),
     38                                if any(field1(:)~=field2(:))
    3939                                        disp([fieldname ' differs']);
    4040                                end
  • issm/trunk/src/m/contrib/chenggong/interpFromMEaSUREsGeotiff.m

    r26701 r27035  
    1 % This function calls src/m/contrib/morlighem/modeldata/interpFromGeotiff.m for multiple times to load all avaliable
    2 % tif data in  /totten_1/ModelData/Greenland/VelMEaSUREs/Jakobshavn_2008_2021/ within the given time period (in decimal years)
    3 % For some reason, each .tif file in this folder contains two sets of data, only the first dataset is useful
     1function dataout = interpFromMEaSUREsGeotiff(X,Y,Tstart,Tend,varargin)
     2%interpFromMEaSUREsGeotiff:
     3%       This function calls src/m/contrib/morlighem/modeldata/interpFromGeotiff.m for multiple times to load all avaliable
     4%       tif data in  /totten_1/ModelData/Greenland/VelMEaSUREs/Jakobshavn_2008_2021/ within the given time period (in decimal years)
     5%       For some reason, each .tif file in this folder contains two sets of data, only the first dataset is useful
     6%
     7%   Usage:
     8%                dataout = interpFromMEaSUREsGeotiff(X,Y,Tstart,Tend, varargin)
     9%
     10%       X, Y are the coordinates of the mesh
     11%       Tstart and Tend decimal year of the start and end time
     12%
     13%   Example:
     14%                       obsData = interpFromMEaSUREsGeotiff(md.mesh.x,md.mesh.y, tstart, tend);
     15%
     16%   Options:
     17%      - 'glacier':  which glacier to look for
     18options    = pairoptions(varargin{:});
     19glacier    = getfieldvalue(options,'glacier','Jakobshavn');
    420
    5 function dataout = interpFromMEaSUREsGeotiff(X,Y,Tstart,Tend)
    6 
    7 foldername = '/totten_1/ModelData/Greenland/VelMEaSUREs/Jakobshavn_2008_2021/';
     21if strcmp(glacier, 'Jakobshavn')
     22        foldername = '/totten_1/ModelData/Greenland/VelMEaSUREs/Jakobshavn_2008_2021/';
     23elseif strcmp(glacier, 'Kangerlussuaq')
     24        foldername = '/totten_1/ModelData/Greenland/VelMEaSUREs/Kangerlussuaq_2006_2021/';
     25elseif strcmp(glacier, 'Store')
     26        foldername = '/totten_1/ModelData/Greenland/VelMEaSUREs/Store_2008_2021/';
     27elseif strcmp(glacier, 'Rink')
     28        foldername = '/totten_1/ModelData/Greenland/VelMEaSUREs/Rink_2008_2022/';
     29else
     30        error(['The velocity data for ', glacier, ' is not available, please download from NSIDC first.']);
     31end
    832
    933% get the time info from file names
  • issm/trunk/src/m/contrib/defleurian/netCDF/export_netCDF.m

    r25836 r27035  
    11function export_netCDF(md,filename)
    2 
    3 %Now going on Real treatment
     2%verbosity of the code, 0 is no messages, 5 is chatty
     3        verbose = 5;
    44        if exist(filename),
    5                 disp(sprintf('File %s allready exist', filename));
    6                 prompt = 'Give a new name or "delete" to replace: ';
    7                 newname = input(prompt,'s');
    8                 if strcmp(newname,'delete')
    9                         delete(filename)
    10                 else
    11                         disp(sprintf('New file name is %s ', newname));
    12                         filename=newname
    13           end
    14   end
     5                delete(filename)
     6                % disp(sprintf('File %s allready exist', filename));
     7                % prompt = 'Give a new name or "delete" to replace: ';
     8                % newname = input(prompt,'s');
     9                % if strcmp(newname,'delete')
     10                %       delete(filename)
     11                % else
     12                %       disp(sprintf('New file name is %s ', newname));
     13                %       filename=newname
     14                % end
     15        end
    1516        %open file and write description
    1617        mode = netcdf.getConstant('NC_NETCDF4');
    17         mode = bitor(mode,netcdf.getConstant('NC_NOCLOBBER'));%NOCLOBBER to avoid overwrite
     18        mode = bitor(mode,netcdf.getConstant('NC_NOCLOBBER')); %NOCLOBBER to avoid overwrite
    1819        ncid = netcdf.create(filename,mode);
    1920        netcdf.putAtt(ncid,netcdf.getConstant('NC_GLOBAL'),'description',['Results for run ' md.miscellaneous.name]);
     
    2122
    2223        %gather geometry and timestepping as dimensions
    23         resfields=fieldnames(md.results);
    24         Duration=size(eval(['md.results. ' resfields{1} ]),2);
     24        if isempty(fieldnames(md.results)),
     25                %results as no field so no time is present
     26                Duration = 0;
     27        else
     28                resfields = fieldnames(md.results);
     29                Duration = size(eval(['md.results. ' resfields{1} ]),2);
     30        end
    2531        if Duration>0,
    26                 StepNum=Duration;
     32                StepNum = Duration;
    2733        else
    2834                StepNum=1;
    29   end
    30 
    31    dimlist=[2,md.mesh.numberofelements,md.mesh.numberofvertices,size(md.mesh.elements,2)];
    32 
    33         %define netcdf dimensions
    34         DimSize(1).index=netcdf.defDim(ncid,'Time',StepNum);
     35        end
     36        DimSize(1).index=netcdf.defDim(ncid,'Time',StepNum);  %time is the first dimension
    3537        [DimSize(1).name,DimSize(1).value]=netcdf.inqDim(ncid,DimSize(1).index);
    3638        DimValue(1)=DimSize(1).value;
    37         DimSize(2).index=netcdf.defDim(ncid,'UnLim',netcdf.getConstant('NC_UNLIMITED'));
     39        DimSize(2).index=netcdf.defDim(ncid,'UnLim',netcdf.getConstant('NC_UNLIMITED')); % we add an unlimited dimension if needed
    3840        [DimSize(2).name,DimSize(2).value]=netcdf.inqDim(ncid,DimSize(2).index);
    3941        DimValue(2)=DimSize(2).value;
     42        % adding mesh related dimensions
     43        dimlist=[2,40,md.mesh.numberofelements,md.mesh.numberofvertices,size(md.mesh.elements,2)];
     44        dimnames=["DictDummy" "StringLength" "EltNum" "VertNum" "VertPerElt"];
     45        if verbose > 0,
     46                disp('===Creating dimensions ===');
     47        end
     48        %define netcdf dimensions
    4049        for i=1:5
     50                % do not add the dimension if it exists already
    4151                if sum(dimlist(i) == DimValue) == 0
    42                         DimSize(i+2).index=netcdf.defDim(ncid,['Dimension' num2str(i+2)],dimlist(i));
     52                        DimSize(i+2).index=netcdf.defDim(ncid,dimnames(i),dimlist(i));
    4353                        [DimSize(i+2).name,DimSize(i+2).value]=netcdf.inqDim(ncid,DimSize(i+2).index);
    4454                        DimValue(i+2)=DimSize(i+2).value;
    4555                end
    4656        end
    47 
    48         typelist=[{'numeric'} {'logical'} {'string'} {'char'} {'cell'}];
    49 
     57        issmclasses = fieldnames(md)';
     58        typelist={'half', 'single','double','int8','int16'...
     59                  ,'int32','int64','uint8','uint16','uint32'...
     60                  ,'uint64','logical','char','string'};  %all malab types that are 0D
     61
     62        for cl=1:length(issmclasses),
     63                subclasses=fieldnames(md.(issmclasses{cl}))';
     64                for sc=1:length(subclasses),
     65                        if sum(strcmp(class(md.(issmclasses{cl}).(subclasses{sc})), typelist)) == 0,
     66                                issmclasses = [issmclasses class(md.(issmclasses{cl}).(subclasses{sc}))];
     67                        end
     68                end
     69        end
    5070        %get all model classes and create respective groups
    5171        groups=fieldnames(md);
     72        if verbose > 0,
     73                disp('===Creating and populating groups===');
     74        end
    5275        for i=1:length(groups),
    53                 disp(sprintf('group name in tree %s ',groups{i}));
     76                if verbose >1,
     77                        disp(sprintf('===Now treating %s===',groups{i}));
     78                end
     79                if strcmp(groups{i}, 'qmu'),
     80                        disp('qmu is skipped until it is more stable');
     81                        continue
     82                end
    5483                groupID=netcdf.defGrp(ncid,groups{i});
    5584                %In each group gather the fields of the class
    56                 groupfields=fieldnames(md.(groups{i}));
    57                 for j=1:length(groupfields),
    58                         Var=md.(groups{i}).(groupfields{j});
     85                fields=fieldnames(md.(groups{i}));
     86                if isempty(fields),
     87                        disp(sprintf("WARNING: md.%s as no fields, we skip it.",groups{i}))
     88                        continue
     89                end
     90                %looping on fields in each group
     91                for j=1:length(fields),
     92                        Var=md.(groups{i}).(fields{j});
     93                        %treatment for lists
    5994                        if isa(Var,'cell')
    60                                 Stdlist=false;
     95                                Stdlist=false;  %first assume it is not a standard list
    6196                                if length(Var) == 0
    62                                         Stdlist=true;
     97                                        Stdlist=true;  %It is empty and so standard (for us)
    6398                                else
    6499                                        for k=1:length(typelist)
    65100                                                if isa(Var{1},typelist{k})
    66                                                         Stdlist=true;
     101                                                        Stdlist=true;  %if the list is of a known type (to matlab) if not it is probably some exotic ISSM stuff
    67102                                                end
    68103                                        end
    69104                                end
    70 
    71                                 netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),'classtype',class(md.(groups{i})));
    72                                 if(Stdlist)
    73                                         disp(sprintf('=====Field name in tree %s ',groupfields{j}));
    74                                         [DimSize,DimValue]=DefCreateVar(ncid,Var,groupID,groupfields{j},DimSize,DimValue);
    75                                 else
    76                                         listsize=length(Var);
    77                                         subgroupID=netcdf.defGrp(groupID,groupfields{j});
    78                                         netcdf.putAtt(subgroupID,netcdf.getConstant('NC_GLOBAL'),'classtype',class(Var));
    79                                         for l=1:listsize
    80                                                 if isprop(Var{l},'name')
    81                                                         lname=Var{l}.name;
    82                                                 elseif isprop(Var{l},'step')
    83                                                         lname=Var{l}.step
    84                                                 else
    85                                                         lname=[class(Var{l}) int2str(l)];
     105                                %print the issm class as a classtype attribute
     106                                klass = class(md.(groups{i}));
     107                                klasstring = strcat(klass, '.',klass);
     108                                netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),'classtype',klasstring);
     109                                if(Stdlist)  % this is a standard or empty list just proceed
     110                                        if verbose > 4,
     111                                                disp(sprintf("=££=creating var for %s.%s with classtype : %s",groups{i}, fields{j}, klasstring))
     112                                        end
     113                                        if ~isempty(Var) && isa(Var{1}, 'char'),  % we have a char array, pad it to a given length
     114                                                Var=char(Var)';
     115                                        end
     116                                        [DimSize,DimValue,varid]=CreateVar(ncid,Var,groupID,fields{j},DimSize,DimValue);
     117                                        if ~isempty(varid),
     118                                                FillVar(Var,groupID,varid);
     119                                        end
     120
     121                                else % this is a list of fields, specific treatment needed (perhaps)
     122                                        if verbose > 4,
     123                                                disp(sprintf("=??=we have a list of fields for %s.%s with classtype : %s",groups{i}, fields{j}, klasstring));
     124                                        end
     125                                        if strcmp(groups{i}, 'outputdefinition'),
     126                                                listsize=length(Var);
     127                                                for k=1:listsize,
     128                                                        subgroupname=md.(groups{i}).(fields{j}){k}.definitionstring;
     129                                                        subgroupID=netcdf.defGrp(groupID,subgroupname);
     130                                                        klass=class(md.(groups{i}).(fields{j}){k});
     131                                                        klasstring = strcat(klass, '.',klass);
     132                                                        netcdf.putAtt(subgroupID,netcdf.getConstant('NC_GLOBAL'),'classtype',klasstring);
     133                                                        subfields=fieldnames(md.(groups{i}).(fields{j}){k});
     134                                                        for l=1:length(subfields)
     135                                                                if verbose > 4,
     136                                                                        disp(sprintf("=--=creating var for %s.%s[%i].%s",groups{i}, fields{j}, k, subfields{l}));
     137                                                                end
     138                                                                Var = md.(groups{i}).(fields{j}){k}.(subfields{l});
     139                                                                if sum(numel(Var) == size(Var)) == 0,  %this is a 2D array or more (and not a vector with dimension 2 = 1)
     140                                                                        Var = Var';
     141                                                                end
     142                                                                [DimSize,DimValue,varid]=CreateVar(ncid,Var,subgroupID,subfields{l},DimSize,DimValue);
     143                                                                if ~isempty(varid),
     144                                                                        FillVar(Var,subgroupID,varid);
     145                                                                end
     146                                                        end
    86147                                                end
    87                                                 listgroupID=netcdf.defGrp(subgroupID,lname);
    88                                                 netcdf.putAtt(listgroupID,netcdf.getConstant('NC_GLOBAL'),'classtype',class(Var{l}));
    89                                                 subfields=fieldnames(Var{l});
    90                                                 for m=1:length(subfields)
    91                                                         if ~strcmp(subfields{m},'outlog')
    92                                                                 [DimSize,DimValue]=DefCreateVar(ncid,Var{l}.(subfields{m}),listgroupID,subfields{m},DimSize,DimValue);
    93                                                         end
     148                                        else
     149                                                disp(sprintf("WARNING: unknown treatment for md.%s",groups{i}));
     150                                        end
     151                                end
     152                        elseif sum(strcmp(class(Var), typelist))==1, %this is a standard matlab class with no subgrouping
     153                                if verbose > 4,
     154                                        disp(sprintf("====creating var for %s.%s", groups{i}, fields{j}))
     155                                end
     156                                klass=class(md.(groups{i}));
     157                                klasstring = strcat(klass, '.',klass);
     158                                netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),'classtype',klasstring);
     159                                if sum(numel(Var) == size(Var)) == 0,  %this is a 2D array or more (and not a vector with dimension 2 = 1)
     160                                        Var = Var';
     161                                end
     162
     163                                [DimSize,DimValue,varid]=CreateVar(ncid,Var,groupID,fields{j},DimSize,DimValue);
     164                                if ~isempty(varid),
     165                                        FillVar(Var,groupID,varid);
     166                                end
     167
     168
     169                        elseif isa(Var,'struct')  % structures need special treatment
     170                                if strcmp(groups{i}, 'results'),
     171                                        klasstring='results.results';
     172                                        netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),'classtype',klasstring);
     173                                        Listsize= length(md.(groups{i}).(fields{j}));
     174                                        subgroupname=fields{j};
     175                                        subgroupID=netcdf.defGrp(groupID,subgroupname);
     176                                        klasstring='results.solutionstep';
     177                                        netcdf.putAtt(subgroupID,netcdf.getConstant('NC_GLOBAL'),'classtype',klasstring);
     178                                        subfields=fieldnames(md.(groups{i}).(fields{j}));
     179                                        if isempty(subfields),
     180                                                disp(sprintf("WARNING: md.%s.%s as no subfields, we skip it.",groups{i}, fields{j}));
     181                                                continue
     182                                        end
     183                                        for k=1:length(subfields),
     184                                                if ~ismember(subfields{k}, {'errlog', 'outlog', 'SolutionType'})
     185                                                        StackedVar=restable();
     186                                                        for l=1:Listsize,
     187                                                                Var = md.(groups{i}).(fields{j})(l).(subfields{k});
     188                                                                if length(Var) == 0,
     189                                                                        %Some variables only have data on the first step
     190                                                                        break
     191                                                                end
     192                                                                lastindex=l;
     193                                                                StackedVar=StackedVar.update(Var);
     194                                                        end
     195                                                        if verbose > 4,
     196                                                                disp(sprintf("=$$=creating var for %s.%s.%s",groups{i}, fields{j}, subfields{k}));
     197                                                                disp(sprintf("last index on the list is %i",lastindex));
     198                                                        end
     199                                                        StackedVar=StackedVar.finalize(lastindex);
     200                                                        [DimSize,DimValue,varid]=CreateVar(ncid,StackedVar,subgroupID,subfields{k},DimSize,DimValue);
     201                                                        if ~isempty(varid),
     202                                                                FillVar(StackedVar,subgroupID,varid);
     203                                                        end
     204                                                elseif ismember(subfields{k}, {'SolutionType'})
     205                                                        %We just add solution type once as an attribute
     206                                                        Var = md.(groups{i}).(fields{j})(1).(subfields{k});
     207                                                        [DimSize,DimValue,varid]=CreateVar(ncid,Var,subgroupID,subfields{k},DimSize,DimValue);
     208                                                        if ~isempty(varid),
     209                                                                FillVar(Var,subgroupID,varid);
     210                                                        end
     211
    94212                                                end
    95213                                        end
    96                                 end
    97                         elseif isa(Var,'struct') && ~strcmp(groupfields{j},'bamg')
    98                                 classtype=class(md.(groups{i}));
    99                                 if strcmp(classtype,'struct')
    100                                         classtype=groups{i};
    101                                 end
    102                                 netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),'classtype',classtype);
    103                                 if length(Var)>1
    104                                         listsize=length(Var);
    105                                         subgroupID=netcdf.defGrp(groupID,groupfields{j});
    106                                         classtype=class(Var);
    107                                         if strcmp(classtype,'struct')
    108                                                 classtype=groups{i};
    109                                         end
    110                                         netcdf.putAtt(subgroupID,netcdf.getConstant('NC_GLOBAL'),'classtype',classtype);
    111                                         for l=1:listsize
    112                                                 if isfield(Var(l),'step')
    113                                                         lname=[int2str(Var(l).step)];
    114                                                 else
    115                                                         lname=[class(Var(l)) int2str(l)];
     214                                elseif isempty(fieldnames(md.(groups{i}).(fields{j}))) % this is an empty struct, jus treat it as normal
     215                                        klass=class(md.(groups{i}));
     216                                        klasstring = strcat(klass, '.',klass);
     217                                        netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),'classtype',klasstring);
     218                                        if verbose > 4,
     219                                                disp(sprintf("=[]=creating var for %s.%s",groups{i}, fields{j}));
     220                                        end
     221
     222                                        [DimSize,DimValue,varid]=CreateVar(ncid,Var,groupID,fields{j},DimSize,DimValue);
     223                                        if ~isempty(varid),
     224                                                FillVar(Var,groupID,varid);
     225                                        end
     226
     227                                else
     228                                        disp(sprintf("WARNING, md.%s.%s is not treated as it does not fall in one of the existing cases with class '%s'.",groups{i}, fields{j}, class(md.(groups{i}).(fields{j}))))
     229                                end
     230                        elseif sum(strcmp(class(Var), issmclasses)) == 1,  % that is an issm class
     231                                if strcmp(class(Var), 'solution'),
     232                                        if verbose > 4,
     233                                                disp(sprintf("=$$=creating var for %s.%s",groups{i}, fields{j}))
     234                                                disp("NEED treatment")
     235                                        end
     236                                elseif strcmp(class(Var), 'dict'),  %we have potential for a dict in py not to sure what it translates to here.
     237                                        if verbose > 4,
     238                                                disp(sprintf("=WW=creating var for %s.%s",groups{i}, fields{j}))
     239                                                disp("NEED Treatment")
     240                                        end
     241
     242                                else
     243                                        klass=class(md.(groups{i}));
     244                                        klasstring = strcat(klass, '.',klass);
     245                                        netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),'classtype',klasstring);
     246                                        subgroupID=netcdf.defGrp(groupID,fields{j});
     247                                        klass=class(md.(groups{i}).(fields{j}));
     248                                        klasstring = strcat(klass, '.',klass);
     249                                        netcdf.putAtt(subgroupID,netcdf.getConstant('NC_GLOBAL'),'classtype',klasstring);
     250                                        subfields=fieldnames(Var);
     251                                        for k=1:length(subfields),
     252                                                if sum(strcmp(subfields{k},["outlog" "errlog"])) == 0,
     253                                                        if verbose > 4,
     254                                                                disp(sprintf("+==+creating var for %s.%s.%s",groups{i}, fields{j}, subfields{k}))
     255                                                        end
     256                                                        Var=md.(groups{i}).(fields{j}).(subfields{k});
     257                                                        [DimSize,DimValue,varid]=CreateVar(ncid,Var,subgroupID,subfields{k},DimSize,DimValue);
     258                                                        if ~isempty(varid),
     259                                                                FillVar(Var,subgroupID,varid);
     260                                                        end
    116261                                                end
    117                                                 classtype=class(Var(l));
    118                                                 if strcmp(classtype,'struct')
    119                                                         classtype=groups{i};
    120                                                 end
    121                                                 listgroupID=netcdf.defGrp(subgroupID,lname);
    122                                                 netcdf.putAtt(listgroupID,netcdf.getConstant('NC_GLOBAL'),'classtype',classtype);
    123                                                 subfields=fieldnames(Var(l));
    124                                                 for m=1:length(subfields)
    125                                                         if ~strcmp(subfields{m},'outlog')
    126                                                                 [DimSize,DimValue]=DefCreateVar(ncid,Var(l).(subfields{m}),listgroupID,subfields{m},DimSize,DimValue);
    127                                                         end
    128                                                 end
    129                                         end
    130                                 else
    131                                         subgroupID=netcdf.defGrp(groupID,groupfields{j});
    132                                         classtype=class(Var);
    133                                         if strcmp(classtype,'struct')
    134                                                 classtype=groups{i};
    135                                         end
    136                                         netcdf.putAtt(subgroupID,netcdf.getConstant('NC_GLOBAL'),'classtype',classtype);
    137                                         subfields=fieldnames(Var);
    138                                         for m=1:length(subfields)
    139                                                 if ~strcmp(subfields{m},'outlog')
    140                                                         [DimSize,DimValue]=DefCreateVar(ncid,Var.(subfields{m}),subgroupID,subfields{m},DimSize,DimValue);
    141                                                 end
    142                                         end
     262                                        end
     263
    143264                                end
    144265                        else
    145                                 netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),'classtype',class(md.(groups{i})));
    146                                 [DimSize,DimValue]=DefCreateVar(ncid,Var,groupID,groupfields{j},DimSize,DimValue);
    147                         end
    148                 end
    149  end
    150  netcdf.close(ncid);
     266                                disp(sprintf("WARNING, md.%s.%s is not treated as it does not fall in one of the existing cases with class '%s'.",groups{i}, fields{j}, class(Var)))
     267                        end
     268                end
     269        end
     270        netcdf.close(ncid);
    151271end
    152272
    153 function [DimSize,DimValue]=DefCreateVar(ncid,Var,groupID,field,DimSize,DimValue,last,md,midfield)
    154         varclass=class(Var);
     273function [DimSize,DimValue,varid]=CreateVar(ncid,Var,groupID,field,DimSize,DimValue)
     274% Grab dimensions
    155275        varsize=size(Var);
    156276        varlength=length(Var);
     277        % treating scalar string or bool as atribute
    157278        if isa(Var,'logical'),
    158279                if Var,
     
    160281                else,
    161282                        LogicString='False';
    162         end
     283                end
    163284                netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),field,LogicString);
     285                varid=[];
     286
    164287        elseif isa(Var,'char'),
    165                 netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),field,Var);
     288                if strcmp(field,'name'),  % it looks like netCDF does not like attributes that are called "name"
     289                        field = 'varname';
     290                end
     291                if size(Var,1) <= 1  %that is a single string or empty
     292                        netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),field,Var);
     293                        varid=[];
     294                else  % that is a character array
     295                        [dims,DimSize,DimValue]=GetDims(ncid,Var,DimSize,DimValue);
     296                        varid = netcdf.defVar(groupID,field,'NC_CHAR',dims);
     297                        if numel(Var)>1
     298                                netcdf.defVarDeflate(groupID,varid,true,true,4);
     299                        end
     300                end
     301
    166302        elseif isa(Var,'double'), %dealing with arrays
    167                 [dims,DimSize,DimValue]=GetDims(ncid,Var,DimSize,DimValue);
    168                 varid = netcdf.defVar(groupID,field,'NC_DOUBLE',dims);
     303                if all(mod(Var, 1) == 0, 'all')  %those are actually integers,
     304                        [dims,DimSize,DimValue]=GetDims(ncid,Var,DimSize,DimValue);
     305                        varid = netcdf.defVar(groupID,field,'NC_INT64',dims);
     306                        if numel(Var)>1
     307                                netcdf.defVarDeflate(groupID,varid,true,true,4);
     308                        end
     309                else
     310                        [dims,DimSize,DimValue]=GetDims(ncid,Var,DimSize,DimValue);
     311                        varid = netcdf.defVar(groupID,field,'NC_DOUBLE',dims);
     312                        if numel(Var)>1
     313                                netcdf.defVarDeflate(groupID,varid,true,true,4);
     314                        end
     315                end
     316        elseif isa(Var,'cell'),
     317                % cells can be a range of things, what are we dealing with here
     318                if isempty(Var),
     319                        netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),field,'emptycell');
     320                        varid=[];
     321                else
     322                        [dims,DimSize,DimValue]=GetDims(ncid,Var,DimSize,DimValue);
     323                        if isa(Var{1}, 'double'),
     324                                varid = netcdf.defVar(groupID,field,'NC_DOUBLE',dims);
     325                                if numel(Var)>1
     326                                        netcdf.defVarDeflate(groupID,varid,true,true,4);
     327                                end
     328                        else
     329                                varid = netcdf.defVar(groupID,field,'NC_CHAR',dims);
     330                                if numel(Var)>1
     331                                        netcdf.defVarDeflate(groupID,varid,true,true,4);
     332                                end
     333                        end
     334                end
     335        elseif isa(Var,'struct'),
     336                if isempty(fieldnames(Var)),
     337                        netcdf.putAtt(groupID,netcdf.getConstant('NC_GLOBAL'),field,'emptystruct');
     338                        varid=[];
     339                else
     340                        %Start by getting the structure fields and size
     341                        [dims,DimSize,DimValue]=GetDims(ncid,Var,DimSize,DimValue);
     342                        varid = netcdf.defVar(groupID,field,'NC_CHAR',dims);
     343                        if numel(Var)>1
     344                                netcdf.defVarDeflate(groupID,varid,true,true,4);
     345                        end
     346                end
     347        else
     348                disp(sprintf('no support for class %s of field %s',class(Var),field));
     349                varid=[];
     350        end
     351        return
     352end
     353
     354
     355function FillVar(Var,groupID,varid)
     356% Grab dimensions
     357        varsize=size(Var);
     358        varlength=length(Var);
     359        % treating scalar string or bool as atribute
     360        if isa(Var,'double'), %dealing with arrays
     361                if all(mod(Var, 1) == 0, 'all')  %those are actually integers,
     362                        Var = int64(Var);
     363                end
    169364                if length(Var)==0,
    170365                        netcdf.putVar(groupID,varid,NaN);
     
    172367                        netcdf.putVar(groupID,varid,Var);
    173368                end
    174         elseif isa(Var,'cell'),
    175                 [dims,DimSize,DimValue]=GetDims(ncid,Var,DimSize,DimValue);
    176                 %dirty hack to be able to pass strings
    177                 varid = netcdf.defVar(groupID,field,'NC_CHAR',dims);
    178                 if length(Var)==0,
    179                         netcdf.putVar(groupID,varid,0,9,'emptycell')
    180                 else
    181                         for i=1:length(Var),
     369        elseif isa(Var,'char'),  % at this point this should be a character array
     370                netcdf.putVar(groupID,varid,Var);
     371        elseif isa(Var,'cell'),  % there can be a number of things in a cell array
     372                for i=1:length(Var),
     373                        if isa(Var{i},'char')  %for characters we limit the size to 40 for now
    182374                                if length(Var)>1,
    183                                         endpoint=[1,min(length(Var{i}),40)];
    184                                         startpoint=[1 0];
    185                                 else
    186                                         endpoint=min(length(Var{i}),40);
     375                                        count=[min(length(Var{i}),40), 1];
     376                                        startpoint=[0 i-1];
     377                                else
     378                                        count=min(length(Var{i}),40);
    187379                                        startpoint=0;
    188380                                end
     381
    189382                                if length(Var{i})>40,
    190                                         netcdf.putVar(groupID,varid,startpoint,extent,Var{i}(1:40))
     383                                        netcdf.putVar(groupID,varid,startpoint,count,Var{i}(1:40));
    191384                                        disp(sprintf('some variable have been truncated'));
    192385                                else
    193                                         netcdf.putVar(groupID,varid,startpoint,endpoint,Var{i})
    194                                 end
     386                                        netcdf.putVar(groupID,varid,startpoint,count,Var{i});
     387                                end
     388                        elseif isa(Var{i},'double')
     389                                startpoint=[i-1];
     390                                count=[1 length(Var{i}) ndims(Var{i})];
     391                                for j=1:ndims(Var{i}),
     392                                        startpoint=[startpoint 0];
     393                                end
     394                                netcdf.putVar(groupID,varid,startpoint,count,Var{i});
     395                        else
     396                                disp(sprintf("WARNING: cell of class %s is not supported.",class(Var{i})))
    195397                        end
    196398                end
    197399        elseif isa(Var,'struct'),
    198400                %Start by getting the structure fields and size
    199                 locfields=fieldnames(Var);
    200                 [dims,DimSize,DimValue]=GetDims(ncid,Var,DimSize,DimValue);
    201                 varid = netcdf.defVar(groupID,field,'NC_CHAR',dims);
    202                 if length(locfields)==0,
    203                         netcdf.putVar(groupID,varid,[0,0],[1,11],'emptystruct')
    204                 else
    205                         for i=1:length(locfields),
    206                                 for j=1:2,
    207                                         if j==1,
    208                                                 CharVar=locfields{i};
    209                                                 if length(CharVar)==0
    210                                                         CharVar='emptystruct';
    211                                                 end
    212                                                 startpoint=[i-1,0,0];
     401                locfields=fieldnames(Var)
     402                for i=1:length(locfields),
     403                        for j=1:2,
     404                                if j==1,
     405                                        CharVar=locfields{i};
     406                                        if length(CharVar)==0
     407                                                CharVar='emptystruct';
     408                                        end
     409                                        startpoint=[i-1,0,0];
     410                                else
     411                                        if isa(Var.(locfields{i}),'char'),
     412                                                CharVar=Var.(locfields{i});
    213413                                        else
    214                                                 if isa(Var.(locfields{i}),'char'),
    215                                                         CharVar=Var.(locfields{i});
    216                                                 else
    217                                                         CharVar=num2str(Var.(locfields{i}));
    218                                                 end
    219                                                 if length(CharVar)==0
    220                                                         CharVar='emptystruct';
    221                                                 end
    222                                                 startpoint=[i-1,1,0];
    223                                         end
    224 
    225                                         extent=[1,1,min(length(CharVar),40)];
    226                                         if length(CharVar)>40,
    227                                                 netcdf.putVar(groupID,varid,startpoint,extent,CharVar(1:40))
    228                                                 disp(sprintf('some variable have been truncated'));
    229                                         else
    230                                                 netcdf.putVar(groupID,varid,startpoint,extent,CharVar)
    231                                         end
     414                                                CharVar=num2str(Var.(locfields{i}));
     415                                        end
     416                                        if length(CharVar)==0
     417                                                CharVar='emptystruct';
     418                                        end
     419                                        startpoint=[i-1,1,0];
     420                                end
     421
     422                                extent=[1,1,min(length(CharVar),40)];
     423                                if length(CharVar)>40,
     424                                        netcdf.putVar(groupID,varid,startpoint,extent,CharVar(1:40));
     425                                        disp(sprintf('some variable have been truncated'));
     426                                else
     427                                        netcdf.putVar(groupID,varid,startpoint,extent,CharVar);
    232428                                end
    233429                        end
    234430                end
    235431        else
    236                 disp(sprintf('no support for class %s of field %s',varclass,field));
    237   end
     432                disp(sprintf('no support for class %s',class(Var)));
     433        end
    238434        return
    239435end
     
    241437function [dims,DimSize,DimValue]=GetDims(ncid,Var,DimSize,DimValue)
    242438        dims=[];
    243         if isa(Var,'cell'),
    244                 varsize=size(Var');
    245         elseif isa(Var,'struct')
     439        celldims=[];
     440        dim=ndims(Var);
     441        if isa(Var,'struct'),
    246442                varsize=length(fieldnames(Var));
    247443        else
    248444                varsize=size(Var);
    249         end
    250         dim=sum(varsize>1);
    251         if dim>0
    252                 for i=1:dim
    253                         indsize=find(varsize(i)==DimValue);
    254                         if length(indsize)>0
    255                                 dims=[dims DimSize(indsize).index];
    256                         else
    257                                 indsize=length(DimSize)+1;
    258                                 DimSize(indsize).index=netcdf.defDim(ncid,['Dimension' num2str(indsize)],varsize(i));
    259                                 [DimSize(indsize).name,DimSize(indsize).value]=netcdf.inqDim(ncid,DimSize(indsize).index);
    260                                 DimValue(indsize)=DimSize(indsize).value;
    261                                 dims=[dims DimSize(indsize).index];
    262                         end
    263                 end
    264         end
    265         %if we have a cell variable we need to add a stringlength dimension
     445                if isa(Var, 'cell')
     446                        %we add the dimension of the cells themselves,
     447                        %that will most probably fail if cells have different sizes
     448                        for i=1:dim,
     449                                newdim=size(Var{i});
     450                                if ~ismember(newdim, celldims),
     451                                        celldims=[celldims newdim];
     452                                end
     453                        end
     454                end
     455        end
     456        varsize=[varsize celldims];
     457        alldim=length(varsize);
     458        if dim>0,
     459                for i=1:alldim,
     460                        if size(Var, i)>1 || i>dim,  %we skip dimensions with zero lenght but want to add dimensions from cells
     461                                indsize=find(varsize(i)==DimValue);
     462                                if length(indsize)>0
     463                                        dims=[dims DimSize(indsize).index];
     464                                else
     465                                        indsize=length(DimSize)+1;
     466                                        DimSize(indsize).index=netcdf.defDim(ncid,['DimNum' num2str(indsize)],varsize(i));
     467                                        [DimSize(indsize).name,DimSize(indsize).value]=netcdf.inqDim(ncid,DimSize(indsize).index);
     468                                        DimValue(indsize)=DimSize(indsize).value;
     469                                        dims=[dims DimSize(indsize).index];
     470                                end
     471                        end
     472                end
     473        end
     474        if isa(Var, 'cell') && isa(Var{1}, 'char'),
     475                %if we have an cell variable with strings we need to add a stringlength
     476                dims=[dims DimSize(4).index];
     477        end
     478        % struct also need an extra dimension 2, but only if non empty
    266479        if isa(Var,'struct'),
    267                 if DimValue(3)~=2
    268                         if DimValue(2)~=2
    269                                 dims=[dims DimSize(1).index];
    270                         else
    271                                 dims=[dims DimSize(2).index];
    272                         end
    273                 else
    274                         dims=[dims DimSize(3).index];
    275                 end
    276         end
    277         if isa(Var,'cell') || isa(Var,'struct'),
    278                 if DimValue(2)~=40
    279                         dims=[dims DimSize(1).index];
    280                 else
    281                         dims=[dims DimSize(2).index];
    282                 end
     480                dims=[dims DimSize(3).index DimSize(4).index];
    283481        end
    284482end
  • issm/trunk/src/m/contrib/defleurian/netCDF/export_netCDF.py

    r26744 r27035  
    11from netCDF4 import Dataset
    22import numpy as np
     3import numpy.ma as ma
    34import time
    45import collections
     
    1314
    1415    def update(self, stepvar):
    15         #if we have a scalar we just add it to the en
     16        #if we have a scalar we just add it to the end
    1617        #we save the size of the current step for further treatment
    1718        if len(np.shape(stepvar)) == 0:
     
    2122        #we save the size of the current step for further treatment
    2223        else:
    23             self.sizes.append(len(stepvar))
    24             for r in stepvar:
    25                 self.data.append(r)
     24            self.sizes.append([np.shape(stepvar)])
     25            stackdat = np.squeeze(stepvar.flatten())
     26            self.data = np.hstack((self.data, stackdat))
    2627
    2728    def finalize(self, rows):
    2829        #we have more scalars than steps, so we have an array
    2930        if len(self.data) > rows:
     31            datasize = np.squeeze(self.sizes)
     32            maxsize = []
     33            try:
     34                dims = np.arange(np.shape(datasize)[1])
     35                for dim in dims:
     36                    maxsize.append(np.nanmax(datasize[:, dim]))
     37            except IndexError:
     38                if datasize.ndim == 0:
     39                    maxsize.append(datasize)
     40                else:
     41                    maxsize.append(np.nanmax(datasize[:]))
     42            findim = np.insert(maxsize, 0, rows)
    3043            #first check if all steps are the same size
    31             SameSize = np.sum(np.asarray(self.sizes) - self.sizes[0]) == 0
     44            if datasize.ndim == 0:
     45                SameSize = True
     46            else:
     47                SameSize = np.sum(np.abs(datasize - datasize[0])) == 0
    3248            if SameSize:
    3349                #same size for all steps, just reshape
    34                 return np.reshape(self.data, newshape=(rows, int(len(self.data) / rows)))
     50                return np.reshape(self.data, newshape=(findim))
    3551            else:
    3652                #different sizes at each steps, first create a table big enough for the biggest step
    3753                startpoint = 0
    38                 datadim = len(np.shape(self.data))
    39                 if datadim == 1:
    40                     outdat = np.nan * np.ones((rows, np.nanmax(self.sizes)))
    41                     for step in range(rows):
    42                         curlen = self.sizes[step]
    43                         outdat[step, :curlen] = self.data[startpoint: startpoint + curlen]
    44                         startpoint += curlen
    45                 elif datadim == 2:
    46                     outdat = np.nan * np.ones((rows, np.nanmax(self.sizes), np.shape(self.data)[1]))
    47                     for step in range(rows):
    48                         curlen = self.sizes[step]
    49                         outdat[step, :curlen, :] = self.data[startpoint: startpoint + curlen]
    50                         startpoint += curlen
    51 
    52                 else:
    53                     print("ERROR, reult treatment cant cope with dimensions above 2")
     54                outdat = np.nan * np.ones(findim)
     55                for step in range(rows):
     56                    #slicer is the data slice in the final array
     57                    slicer = [slice(0, d) for d in datasize[step, :]]
     58                    slicer = np.insert(slicer, 0, step)
     59                    curlen = int(np.prod(datasize[step, :]))
     60                    outdat[tuple(slicer)] = np.reshape(self.data[startpoint:startpoint + curlen], newshape=(datasize[step, :]))
     61                    startpoint += curlen
     62                #outmasked = ma.masked_array(outdat, mask=np.where(np.isnan(outdat), 1, 0))
    5463                return outdat
    55         #as much scalars as stpes (or less) so just one value per step
    56         else:
    57             return np.asarray(self.data)
     64        #as much scalars as steps (or less) so just one value per step
     65        else:
     66            return np.squeeze(np.asarray(self.data))
    5867
    5968
     
    8897    dimindex = 2
    8998    #add mesh related dimension that we know are needed
    90     dimlist = [2, md.mesh.numberofelements, md.mesh.numberofvertices, np.shape(md.mesh.elements)[1]]
    91     dimnames = ['DictDummy', 'EltNum', 'VertNum', 'VertPerElt']
     99    dimlist = [2, 40, md.mesh.numberofelements, md.mesh.numberofvertices, np.shape(md.mesh.elements)[1]]
     100    dimnames = ['DictDummy', 'StringLength', 'EltNum', 'VertNum', 'VertPerElt']
    92101    if verbose > 0:
    93102        print('===Creating dimensions ===')
     
    121130        # looping on fields in each group
    122131        for field in fields:
     132            Var = md.__dict__[group].__dict__[field]
    123133            # Special treatment for list fields
    124             if type(md.__dict__[group].__dict__[field]) == list:
     134            if type(Var) == list:
    125135                StdList = False
    126                 if len(md.__dict__[group].__dict__[field]) == 0:
     136                if len(Var) == 0:
    127137                    StdList = True  #this is an empty list
    128138                else:
    129139                    #returns False for exotic types (typicaly results)
    130                     StdList = type(md.__dict__[group].__dict__[field][0]) in typelist
     140                    StdList = type(Var[0]) in typelist
    131141                klass = type(md.__dict__[group]).__module__ + '.' + type(md.__dict__[group]).__name__
    132142                NCgroup.__setattr__('classtype', klass)
     
    134144                    if verbose > 4:
    135145                        print("=££=creating var for {}.{} with classtype : {}".format(group, field, klass))
    136                     Var = md.__dict__[group].__dict__[field]
    137146                    Var = SqueezeVar(Var)
    138147                    DimDict, ncvar = CreateVar(NCData, Var, field, NCgroup, DimDict)
     
    141150                else:  # this is a list of fields, specific treatment needed (usually results or outputdefinitions)
    142151                    if verbose > 4:
    143                         print("list of fields happens for {}.{} with classtype : {}".format(group, field, klass))
    144                     Listsize = len(md.__dict__[group].__dict__[field])
     152                        print("=??=we have a list of fields for {}.{} with classtype : {}".format(group, field, klass))
     153                    Listsize = len(Var)
    145154                    if group == 'results':  #for results we reshape the datas following time rather than subgrouping
    146155                        Subgroup = NCgroup.createGroup(str(field))
     
    155164                            subfields = dict.keys(md.__dict__[group].__dict__[field].__getitem__(0))
    156165                        for subfield in subfields:
    157                             if subfield not in['errlog', 'outlog']:
     166                            if subfield not in ['errlog', 'outlog']:
    158167                                StackedVar = ResTable()
    159168                                #first loop over the field (result type) to find the index of the last subfield (variable)
     
    172181                                    StackedVar.update(Var)
    173182                                if verbose > 4:
    174                                     print("=$$=creating var for {}.{}.{}".format(group, field, subfield))
     183                                    print("=@@=creating var for {}.{}.{}".format(group, field, subfield))
    175184                                    print("last index of the list is {}".format(lastindex))
    176185                                StackedVar = SqueezeVar(StackedVar.finalize(int(lastindex)))
     
    238247                        subfields = dict.keys(md.__dict__[group].__dict__[field].__getitem__(0))
    239248                    for subfield in subfields:
    240                         if subfield not in['errlog', 'outlog']:
     249                        if subfield not in ['errlog', 'outlog']:
    241250                            StackedVar = ResTable()
    242251                            for listindex in range(0, Listsize):
     
    245254                                    lastindex = listindex + 1
    246255                                except AttributeError:
    247                                     Var = md.__dict__[group].__dict__[field].__getitem__(listindex)[subfield]
     256                                    Var = md.__dict__[group].__dict__[field].__dict__[subfield]
     257                                    lastindex = listindex
    248258                                except KeyError:
    249259                                    #Some fields only exist for the first step
    250260                                    lastindex = listindex
    251                                     continue
     261                                    break
    252262                                Var = SqueezeVar(Var)
    253263                                StackedVar.update(Var)
     
    289299                                FillVar(ncvar, Var)
    290300            else:
    291                 print("WARNING, md.{}.{} is not treated as it does not fall in one of the existing cases.".format(str(group), str(field)))
     301                print("WARNING, md.{}.{} is not treated as it does not fall in one of the existing cases.".format(group, field))
    292302
    293303    NCData.close()
     
    305315        if val_type.startswith('<U'):
    306316            val_type = 'stringarray'
     317            print(var)
    307318    except AttributeError:
    308319        val_type = type(var)
     
    329340        if field == 'name':  # it looks like netCDF does not like attributes that are called "name"
    330341            field = 'varname'
    331         Group.__setattr__(str(field).swapcase(), str(var))
     342        Group.__setattr__(str(field), str(var))
    332343        ncvar = None
    333344    # numpy array of strings
    334345    elif val_type == "stringarray":
    335346        #if all strings are the same set it as an attribute
    336         if all(var == var[0]):
     347        try:
     348            samestring = all(var == var[0])
     349        except IndexError:
     350            #Only one string
     351            samestring = True
     352        if samestring:
    337353            if field == 'name':
    338354                field = 'varname'
    339             Group.__setattr__(str(field).swapcase(), str(var[0]))
     355            try:
     356                Group.__setattr__(str(field), str(var[0]))
     357            except IndexError:
     358                Group.__setattr__(str(field), str(var))
    340359            ncvar = None
    341360        else:
     
    355374            dimensions, DimDict = GetDim(NCData, val_shape, val_type, DimDict, val_dim)
    356375            ncvar = Group.createVariable(str(field), nctype, dimensions=dimensions, zlib=True)
    357     # treating bool tables and dict as string tables
    358     elif val_type in [collections.OrderedDict, dict, 'bool']:
     376    # treating dict as string tables
     377    elif val_type in [collections.OrderedDict, dict]:
    359378        if val_shape in [(), (0,), 0]:
    360379            ncvar = Group.createVariable(str(field), str, zlib=True)
     
    362381            dimensions, DimDict = GetDim(NCData, val_shape, val_type, DimDict, val_dim)
    363382            ncvar = Group.createVariable(str(field), str, dimensions=dimensions, zlib=True)
    364     # Now dealing with numeric variables
    365     elif val_type in [float, 'float64', np.float64, int, 'int64']:
     383    # treating bool as integers
     384    elif val_type == 'bool':
     385        if val_shape in [(), (0,), 0]:
     386            ncvar = Group.createVariable(str(field), int, zlib=True)
     387        else:
     388            dimensions, DimDict = GetDim(NCData, val_shape, val_type, DimDict, val_dim)
     389            ncvar = Group.createVariable(str(field), int, dimensions=dimensions, zlib=True)
     390    # Now dealing with doubles, we convert them to int if possible
     391    elif val_type in [float, 'float64', np.float64]:
     392        try:
     393            #check if we are integer and under C long overflow also skip empty arrays
     394            IsInt = np.sum(np.mod(var, 1)) == 0 and np.all(abs(var) < 2147483647) and len(var) > 0
     395        except TypeError:
     396            #check if we are integer and under C long overflow
     397            IsInt = np.mod(var, 1) == 0 and abs(var) < 2147483647
     398        if IsInt:
     399            val_type = 'int64'
     400        if val_shape in [(), (0,), 0] and not SupDim:
     401            ncvar = Group.createVariable(str(field), TypeDict[val_type], zlib=True)
     402        else:
     403            dimensions, DimDict = GetDim(NCData, val_shape, val_type, DimDict, val_dim)
     404            if SupDim:
     405                dimensions = SupDim + dimensions
     406            ncvar = Group.createVariable(str(field), TypeDict[val_type], dimensions=dimensions, zlib=True)
     407    elif val_type in [int, 'int64']:
    366408        if val_shape in [(), (0,), 0] and not SupDim:
    367409            ncvar = Group.createVariable(str(field), TypeDict[val_type], zlib=True)
     
    410452    elif val_type == 'bool':
    411453        for elt in range(0, val_shape[0]):
    412             ncvar[elt] = str(invar[elt])
     454            ncvar[elt] = int(invar[elt])  #str(invar[elt])
    413455    # treating dictionaries as tables of strings
    414456    elif val_type in [collections.OrderedDict, dict]:
  • issm/trunk/src/m/contrib/larour/mdanalysis.m

    r25836 r27035  
    16001600                        if strncmpi(fieldv,'Mask',4),
    16011601                                contourexp=[tempname '.exp'];
    1602                                 expcontourlevelzero(md.icecaps{i},field,0, contourexp);
     1602                                isoline(md.icecaps{i},field,'output',contourexp);
    16031603                                contourlevels=1;
    16041604
    16051605                                if diff,
    16061606                                        contourdiffexp=[tempname '.exp'];
    1607                                         expcontourlevelzero(md.icecaps{i},dfield,0, contourdiffexp);
     1607                                        isoline(md.icecaps{i},dfield,'output',contourdiffexp);
    16081608                                end
    16091609                        end
  • issm/trunk/src/m/contrib/morlighem/modeldata/interpBamber2001.m

    r23873 r27035  
    88                bamber2001bedpath ='/home/ModelData/Greenland/Bamber2001/bedrock.mat';
    99                bamber2001thxpath ='/home/ModelData/Greenland/Bamber2001/thickness.mat';
     10        case {'totten'}
     11                bamber2001bedpath ='/totten_1/ModelData/Greenland/Bamber2001/bedrock.mat';
     12                bamber2001thxpath ='/totten_1/ModelData/Greenland/Bamber2001/thickness.mat';
    1013        otherwise
    1114                error('machine not supported yet');
  • issm/trunk/src/m/contrib/morlighem/modeldata/interpBamber2013.m

    r23873 r27035  
    2222        case {'ronne'}
    2323                bamber2013nc='/home/ModelData/Greenland/Bamber2013/Greenland_bedrock_topography_V3.nc';
     24        case {'totten'}
     25                bamber2013nc='/totten_1/ModelData/Greenland/Bamber2013/Greenland_bedrock_topography_V3.nc';
    2426        otherwise
    2527                error('machine not supported yet');
  • issm/trunk/src/m/contrib/morlighem/modeldata/interpBedmachineAntarctica.m

    r26744 r27035  
    2828if nargin<5
    2929        ncdate='2020-07-15'; %BedMachine v2
    30         ncdate='2021-11-16'; %BedMachine v2
     30        ncdate='2021-11-16'; %new
    3131end
    3232basename = 'BedMachineAntarctica';
  • issm/trunk/src/m/contrib/morlighem/modeldata/interpBedmachineGreenland.m

    r26744 r27035  
    3030        ncdate='2017-09-25'; %BedMachine v3
    3131        ncdate='2020-04-14';
     32        ncdate='2021-08-27';
     33        ncdate='2022-03-17';
    3234end
    3335basename = 'BedMachineGreenland';
  • issm/trunk/src/m/contrib/morlighem/modeldata/interpDhdt.m

    r23873 r27035  
    44        case {'ronne'}
    55                dhdtpath='/home/ModelData/Greenland/DHDT/dhdt0306.tif';
     6        case {'totten'}
     7                dhdtpath='/totten_1/ModelData/Greenland/DHDT/dhdt0306.tif';
    68        otherwise
    79                error('machine not supported yet');
  • issm/trunk/src/m/contrib/morlighem/modeldata/interpGimpdem.m

    r23873 r27035  
    66        case {'ronne'}
    77                howatpath='/home/ModelData/Greenland/gimpdem/gimpdem_90m.tif';
     8        case {'totten'}
     9                howatpath='/totten_1/ModelData/Greenland/gimpdem/gimpdem_90m.tif';
    810        otherwise
    911                error('machine not supported yet');
  • issm/trunk/src/m/contrib/morlighem/modeldata/interpJakobsson2020.m

    r25836 r27035  
    44        case {'ronne'}
    55                ncpath ='/home/ModelData/Greenland/IBCAO/IBCAO_v4_200m.nc';
     6        case {'totten'}
     7                ncpath ='/totten_1/ModelData/Greenland/IBCAO/IBCAO_v4_200m.nc';
    68        otherwise
    79                error('machine not supported yet');
     
    3941
    4042if nargout==2,
    41         ncpath ='/home/ModelData/Greenland/IBCAO/IBCAO_v4_200m_TID.nc';
     43        ncpath ='/totten_1/ModelData/Greenland/IBCAO/IBCAO_v4_200m_TID.nc';
    4244        disp('   -- Jakobsson2020: loading source');
    4345        data = double(ncread(ncpath,'z',[id1x id1y],[id2x-id1x+1 id2y-id1y+1],[1 1]))';
  • issm/trunk/src/m/contrib/morlighem/modeldata/interpMouginotAnt2019.m

    r25836 r27035  
    55        case {'ronne'}
    66                nc = '/home/ModelData/Antarctica/MouginotVel/v_mix.v13Mar2019.nc';
     7        case {'totten'}
     8                nc = '/totten_1/ModelData/Antarctica/MouginotVel/v_mix.v8Jul2019.nc';
    79        otherwise
    810                error('hostname not supported yet');
  • issm/trunk/src/m/contrib/morlighem/modeldata/interpRACMO1km.m

    r23873 r27035  
    44        case {'ronne'}
    55                rootname='/home/ModelData/Greenland/RACMO2_1km/SMB_MEAN1960-1989_150m.nc';
     6        case {'totten'}
     7                rootname='/totten_1/ModelData/Greenland/RACMO2_1km/SMB_MEAN1960-1989_150m.nc';
    68        otherwise
    79                error('machine not supported yet');
  • issm/trunk/src/m/contrib/morlighem/modeldata/interpRignotIceShelfMelt.m

    r23873 r27035  
    44        case {'ronne'}
    55                rignotmelt='/home/ModelData/Antarctica/RignotMeltingrate/Ant_MeltingRate.nc';
     6        case {'totten'}
     7                rignotmelt='/totten_1/ModelData/Antarctica/RignotMeltingrate/Ant_MeltingRate.nc';
    68        case {'thwaites','murdo','astrid'}
    79                rignotmelt=['/home/seroussi/Data/Ant_MeltingRate.nc'];
  • issm/trunk/src/m/coordsystems/ll2xy.m

    r26744 r27035  
    4040end
    4141
     42%Move to CoordTransform now...
     43if exist('CoordTransform_matlab')==3
     44        disp('Calling CoordTransform instead, make sure to change your MATLAB script');
     45        if sgn==+1
     46                assert(delta==45); assert(slat ==70);
     47                [x y]=CoordTransform(lat,lon,'EPSG:4326','EPSG:3413');
     48                return;
     49        else
     50                assert(delta==0); assert(slat ==71);
     51                [x y]=CoordTransform(lat,lon,'EPSG:4326','EPSG:3031');
     52                return;
     53        end
     54end
     55
    4256% Conversion constant from degrees to radians
    4357cde  = 57.29577951;
  • issm/trunk/src/m/coordsystems/xy2ll.m

    r24313 r27035  
    3434        help xy2ll
    3535        error('bad usage');
     36end
     37
     38%Move to CoordTransform now...
     39if exist('CoordTransform_matlab')==3
     40        disp('Calling CoordTransform instead, make sure to change your MATLAB script');
     41        if sgn==+1
     42                assert(delta==45); assert(slat ==70);
     43                [lat lon]=CoordTransform(x, y,'EPSG:3413','EPSG:4326');
     44                return;
     45        else
     46                assert(delta==0); assert(slat ==71);
     47                [lat lon]=CoordTransform(x, y,'EPSG:3031','EPSG:4326');
     48                return;
     49        end
    3650end
    3751
  • issm/trunk/src/m/dev/issmversion.m

    r26744 r27035  
    1717disp(['Compiled on ' IssmConfig('HOST_VENDOR') ' ' IssmConfig('HOST_OS') ' ' IssmConfig('HOST_ARCH') ' by ' IssmConfig('USER_NAME')]);
    1818disp([' ']);
    19 disp(['Copyright (c) 2009-2021 California Institute of Technology']);
     19disp(['Copyright (c) 2009-2022 California Institute of Technology']);
    2020disp([' ']);
    2121disp(['    to get started type: issmdoc']);
  • issm/trunk/src/m/dev/issmversion.py

    r26744 r27035  
    1616print(' ')
    1717print(('Build date: ' + IssmConfig('PACKAGE_BUILD_DATE')[0]))
    18 print('Copyright (c) 2009-2021 California Institute of Technology')
     18print('Copyright (c) 2009-2022 California Institute of Technology')
    1919print(' ')
    2020print('    to get started type: issmdoc')
  • issm/trunk/src/m/exp/contourlevelzero.m

    r26744 r27035  
    1 function contours=contourlevelzero(md,mask,level)
    2 %CONTOURLEVELZERO - figure out the zero level (or offset thereof, specified by the level value)
    3 %                   of a vectorial mask, and vectorialize it into an exp or shp compatible
    4 %structure.
    5 %
    6 %   Usage:
    7 %      contours=contourlevelzero(md,mask,level)
    8 %
    9 %   See also: PLOT_CONTOUR
     1function contours=contourlevelzero(md,mask,level,varargin)
    102
    11 %process data
    12 if dimension(md.mesh)==3,
    13 %       error('contourlevelzero error message: routine not supported for 3d meshes, project on a layer');
    14         x = md.mesh.x2d;
    15         y = md.mesh.y2d;
    16         index=md.mesh.elements2d;
    17 else
    18         x=md.mesh.x;
    19         y=md.mesh.y;
    20         index=md.mesh.elements;
    21 end
    22 
    23 if isprop(md.mesh,'z'),
    24         z=md.mesh.z;
    25 else
    26         z=zeros(md.mesh.numberofvertices,1);
    27 end
    28 
    29 if isempty(mask), error('mask provided is empty'); end
    30 if dimension(md.mesh)==3,
    31         if length(mask)~=md.mesh.numberofvertices2d, error('mask provided should be specified at the vertices of the mesh'); end
    32 else
    33         if length(mask)~=md.mesh.numberofvertices, error('mask provided should be specified at the vertices of the mesh'); end
    34 end
    35 
    36 %initialization of some variables
    37 numberofelements=size(index,1);
    38 elementslist=1:numberofelements;
    39 c=[];
    40 h=[];
    41 
    42 %get unique edges in mesh
    43 %1: list of edges
    44 edges=[index(:,[1,2]); index(:,[2,3]); index(:,[3,1])];
    45 %2: find unique edges
    46 [edges,I,J]=unique(sort(edges,2),'rows');
    47 %3: unique edge numbers
    48 vec=J;
    49 %4: unique edges numbers in each triangle (2 triangles sharing the same edge will have
    50 %   the same edge number)
    51 edges_tria=[vec(elementslist), vec(elementslist+numberofelements), vec(elementslist+2*numberofelements)];
    52 
    53 %segments [nodes1 nodes2]
    54 Seg1=index(:,[1 2]);
    55 Seg2=index(:,[2 3]);
    56 Seg3=index(:,[3 1]);
    57 
    58 %segment numbers [1;4;6;...]
    59 Seg1_num=edges_tria(:,1);
    60 Seg2_num=edges_tria(:,2);
    61 Seg3_num=edges_tria(:,3);
    62 
    63 %value of data on each tips of the segments
    64 Data1=mask(Seg1);
    65 Data2=mask(Seg2);
    66 Data3=mask(Seg3);
    67 
    68 %get the ranges for each segment
    69 Range1=sort(Data1,2);
    70 Range2=sort(Data2,2);
    71 Range3=sort(Data3,2);
    72 
    73 %find the segments that contain this value
    74 pos1=(Range1(:,1)<level & Range1(:,2)>=level);
    75 pos2=(Range2(:,1)<level & Range2(:,2)>=level);
    76 pos3=(Range3(:,1)<level & Range3(:,2)>=level);
    77 
    78 %get elements
    79 poselem12=(pos1 & pos2);
    80 poselem13=(pos1 & pos3);
    81 poselem23=(pos2 & pos3);
    82 poselem=find(poselem12 | poselem13 | poselem23);
    83 numelems=length(poselem);
    84 
    85 %if no element has been flagged, skip to the next level
    86 if numelems==0,
    87         warning('contourlevelzero warning message: no elements found with corresponding level value in mask');
    88         contours=struct([]);
    89         return;
    90 end
    91 
    92 %go through the elements and build the coordinates for each segment (1 by element)
    93 x1=zeros(numelems,1);
    94 x2=zeros(numelems,1);
    95 y1=zeros(numelems,1);
    96 y2=zeros(numelems,1);
    97 z1=zeros(numelems,1);
    98 z2=zeros(numelems,1);
    99 
    100 edge_l=zeros(numelems,2);
    101 
    102 for j=1:numelems,
    103 
    104         weight1=(level-Data1(poselem(j),1))/(Data1(poselem(j),2)-Data1(poselem(j),1));
    105         weight2=(level-Data2(poselem(j),1))/(Data2(poselem(j),2)-Data2(poselem(j),1));
    106         weight3=(level-Data3(poselem(j),1))/(Data3(poselem(j),2)-Data3(poselem(j),1));
    107 
    108         if poselem12(poselem(j));
    109 
    110                 x1(j)=x(Seg1(poselem(j),1))+weight1*(x(Seg1(poselem(j),2))-x(Seg1(poselem(j),1)));
    111                 x2(j)=x(Seg2(poselem(j),1))+weight2*(x(Seg2(poselem(j),2))-x(Seg2(poselem(j),1)));
    112                 y1(j)=y(Seg1(poselem(j),1))+weight1*(y(Seg1(poselem(j),2))-y(Seg1(poselem(j),1)));
    113                 y2(j)=y(Seg2(poselem(j),1))+weight2*(y(Seg2(poselem(j),2))-y(Seg2(poselem(j),1)));
    114                 z1(j)=z(Seg1(poselem(j),1))+weight1*(z(Seg1(poselem(j),2))-z(Seg1(poselem(j),1)));
    115                 z2(j)=z(Seg2(poselem(j),1))+weight2*(z(Seg2(poselem(j),2))-z(Seg2(poselem(j),1)));
    116 
    117                 edge_l(j,1)=Seg1_num(poselem(j));
    118                 edge_l(j,2)=Seg2_num(poselem(j));
    119 
    120         elseif poselem13(poselem(j)),
    121 
    122                 x1(j)=x(Seg1(poselem(j),1))+weight1*(x(Seg1(poselem(j),2))-x(Seg1(poselem(j),1)));
    123                 x2(j)=x(Seg3(poselem(j),1))+weight3*(x(Seg3(poselem(j),2))-x(Seg3(poselem(j),1)));
    124                 y1(j)=y(Seg1(poselem(j),1))+weight1*(y(Seg1(poselem(j),2))-y(Seg1(poselem(j),1)));
    125                 y2(j)=y(Seg3(poselem(j),1))+weight3*(y(Seg3(poselem(j),2))-y(Seg3(poselem(j),1)));
    126                 z1(j)=z(Seg1(poselem(j),1))+weight1*(z(Seg1(poselem(j),2))-z(Seg1(poselem(j),1)));
    127                 z2(j)=z(Seg3(poselem(j),1))+weight3*(z(Seg3(poselem(j),2))-z(Seg3(poselem(j),1)));
    128 
    129                 edge_l(j,1)=Seg1_num(poselem(j));
    130                 edge_l(j,2)=Seg3_num(poselem(j));
    131 
    132         elseif poselem23(poselem(j)),
    133 
    134                 x1(j)=x(Seg2(poselem(j),1))+weight2*(x(Seg2(poselem(j),2))-x(Seg2(poselem(j),1)));
    135                 x2(j)=x(Seg3(poselem(j),1))+weight3*(x(Seg3(poselem(j),2))-x(Seg3(poselem(j),1)));
    136                 y1(j)=y(Seg2(poselem(j),1))+weight2*(y(Seg2(poselem(j),2))-y(Seg2(poselem(j),1)));
    137                 y2(j)=y(Seg3(poselem(j),1))+weight3*(y(Seg3(poselem(j),2))-y(Seg3(poselem(j),1)));
    138                 z1(j)=z(Seg2(poselem(j),1))+weight2*(z(Seg2(poselem(j),2))-z(Seg2(poselem(j),1)));
    139                 z2(j)=z(Seg3(poselem(j),1))+weight3*(z(Seg3(poselem(j),2))-z(Seg3(poselem(j),1)));
    140 
    141                 edge_l(j,1)=Seg2_num(poselem(j));
    142                 edge_l(j,2)=Seg3_num(poselem(j));
    143         else
    144                 %it shoud not go here
    145         end
    146 end
    147 
    148 %now that we have the segments, we must try to connect them...
    149 
    150 %loop over the subcontours
    151 contours=struct([]);
    152 
    153 while ~isempty(edge_l),
    154 
    155         %take the right edge of the second segment and connect it to the next segments if any
    156         e1=edge_l(1,1);   e2=edge_l(1,2);
    157         xc=[x1(1);x2(1)]; yc=[y1(1);y2(1)]; zc=[z1(1);z2(1)];
    158 
    159 
    160         %erase the lines corresponding to this edge
    161         edge_l(1,:)=[];
    162         x1(1)=[]; x2(1)=[];
    163         y1(1)=[]; y2(1)=[];
    164         z1(1)=[]; z2(1)=[];
    165 
    166         [ro1,co1]=find(edge_l==e1);
    167 
    168         while ~isempty(ro1)
    169 
    170                 if co1==1,
    171                         xc=[x2(ro1);xc]; yc=[y2(ro1);yc];zc=[z2(ro1);zc];
    172 
    173                         %next edge:
    174                         e1=edge_l(ro1,2);
    175 
    176                 else
    177                         xc=[x1(ro1);xc]; yc=[y1(ro1);yc];zc=[z1(ro1);zc];
    178 
    179                         %next edge:
    180                         e1=edge_l(ro1,1);
    181                 end
    182 
    183                 %erase the lines of this
    184                 edge_l(ro1,:)=[];
    185                 x1(ro1)=[]; x2(ro1)=[];
    186                 y1(ro1)=[]; y2(ro1)=[];
    187                 z1(ro1)=[]; z2(ro1)=[];
    188 
    189                 %next connection
    190                 [ro1,co1]=find(edge_l==e1);
    191         end
    192 
    193         %same thing the other way (to the right)
    194         [ro2,co2]=find(edge_l==e2);
    195 
    196         while ~isempty(ro2)
    197 
    198                 if co2==1,
    199                         xc=[xc;x2(ro2)]; yc=[yc;y2(ro2)];zc=[zc;z2(ro2)];
    200 
    201                         %next edge:
    202                         e2=edge_l(ro2,2);
    203                 else
    204                         xc=[xc;x1(ro2)]; yc=[yc;y1(ro2)]; zc=[zc;z1(ro2)];
    205 
    206                         %next edge:
    207                         e2=edge_l(ro2,1);
    208                 end
    209 
    210                 %erase the lines of this
    211                 edge_l(ro2,:)=[];
    212                 x1(ro2)=[]; x2(ro2)=[];
    213                 y1(ro2)=[]; y2(ro2)=[];
    214                 z1(ro2)=[]; z2(ro2)=[];
    215 
    216                 %next connection
    217                 [ro2,co2]=find(edge_l==e2);
    218         end
    219 
    220         %save xc,yc contour:
    221         contours(end+1).x=xc;
    222         contours(end).y=yc;
    223         contours(end).z=zc;
    224         contours(end).name='';
    225         contours(end).nods=length(xc);
    226         contours(end).density=1;
    227         contours(end).closed=0;
    228 
    229 end
     3        error('this function has been renamed: A = isoline(md,mask);');
  • issm/trunk/src/m/exp/expcontourlevelzero.m

    r26744 r27035  
    11function expcontourlevelzero(md,mask,level,filename)
    2 %EXPCONTOURLEVELZERO - write an Argus file from a structure recovered from running contourlevelzero
    3 %
    4 %   Usage:
    5 %      expcontourlevelzero(md,mask,level,filename)
    6 %
    7 %   Example:
    8 %      expcontourlevelzero(md,md.geometry.thickness,10, 'Level0.exp');
    9 %      expcontourlevelzero(md,md.mask.ocean_levelset,0, 'Level0.exp');
    10 %
    11 %   See also CONTOURLEVELZERO, EXPWRITE
    122
    13 contours=contourlevelzero(md,mask,level);
    14 expwrite(contours,filename);
     3error(['this function has been renamed: isoline(md,mask,''output'',''' filename ''');']);
  • issm/trunk/src/m/exp/exptool.m

    r24313 r27035  
    137137%plot existing profile if any
    138138hold on
     139disableDefaultInteractivity(gca); %disables the built-in interactions for the specified axes
    139140
    140141%Build backup structre for do and redo
  • issm/trunk/src/m/exp/expwrite.py

    r26744 r27035  
    77    This routine writes an Argus file from a dict containing the fields:
    88    x and y of the coordinates of the points.
    9     The first argument is the list containing the points coordinates and the 
     9    The first argument is the list containing the points coordinates and the
    1010    second one the file to be written.
    1111
     
    2020
    2121    fid = open(filename, 'w')
    22     for x, y in zip(contours['x'], contours['y']):
    23         if len(x) != len(y):
    24             raise RuntimeError('contours x and y coordinates must be of identical size')
    25 
    26         if 'name' in contours:
    27             fid.write('{}{}\n'.format('# Name:', contours['name']))
     22    #if it is a list we need to loop on several contours
     23    if isinstance(contours, list):
     24        for contour in contours:
     25            #if it is some kind of array it is a contour and we loop on indexes
     26            if isinstance(contour['x'], (list, tuple, np.ndarray)):
     27                writegeomlist(contour, fid, filename)
     28            #else it is an index and we just write it down
     29            else:
     30                writegeom(contour, fid, filename)
     31    #if it is a dict type it means just one contour
     32    else:
     33        #if it is some kind of array it is a contour and we loop on indexes
     34        if isinstance(contours['x'], (list, tuple, np.ndarray)):
     35            writegeomlist(contours, fid, filename)
     36        #else it is an index and we just write it down
    2837        else:
    29             fid.write('{}{}\n'.format('# Name:', filename))
    30 
    31         fid.write('{}\n'.format('## Icon:0'))
    32         fid.write('{}\n'.format('# Points Count Value'))
    33         if 'density' in contours:
    34             if isinstance(contours['density'], int):
    35                 fid.write('{} {}\n'.format(np.size(x), contours['density']))
    36             else:
    37                 fid.write('{} {}\n'.format(np.size(x), 1.))
    38         else:
    39             fid.write('{} {}\n'.format(np.size(x), 1.))
    40         fid.write('{}\n'.format('# X pos Y pos'))
    41         for xi, yi in zip(x, y):
    42             fid.write('%10.10f %10.10f\n' % (xi, yi))
    43         fid.write('\n')
     38            writegeom(contours, fid, filename)
    4439
    4540    fid.close()
     41
     42
     43def writegeomlist(contour, fid, filename):
     44    if len(contour['x']) != len(contour['y']):
     45        raise RuntimeError('contours x and y coordinates must be of identical size')
     46    if 'name' in contour:
     47        fid.write('{}{}\n'.format('## Name:', contour['name']))
     48    else:
     49        fid.write('{}{}\n'.format('## Name:', filename))
     50
     51    fid.write('{}\n'.format('## Icon:0'))
     52    fid.write('{}\n'.format('# Points Count Value'))
     53    if 'density' in contour:
     54        if isinstance(contour['density'], int):
     55            fid.write('{} {}\n'.format(np.size(contour['x']), contour['density']))
     56        else:
     57            fid.write('{} {}\n'.format(np.size(contour['x']), 1.))
     58    else:
     59        fid.write('{} {}\n'.format(np.size(contour['x']), 1.))
     60    fid.write('{}\n'.format('# X pos Y pos'))
     61    for x, y in zip(contour['x'], contour['y']):
     62        fid.write('%10.10f %10.10f\n' % (x, y))
     63    fid.write('\n')
     64
     65
     66def writegeom(contour, fid, filename):
     67    if 'name' in contour:
     68        fid.write('{}{}\n'.format('## Name:', contour['name']))
     69    else:
     70        fid.write('{}{}\n'.format('## Name:', filename))
     71
     72    fid.write('{}\n'.format('## Icon:0'))
     73    fid.write('{}\n'.format('# Points Count Value'))
     74    if 'density' in contour:
     75        if isinstance(contour['density'], int):
     76            fid.write('{} {}\n'.format(1, contour['density']))
     77        else:
     78            fid.write('{} {}\n'.format(1, 1.))
     79    else:
     80        fid.write('{} {}\n'.format(1, 1.))
     81    fid.write('{}\n'.format('# X pos Y pos'))
     82    fid.write('%10.10f %10.10f\n' % (contour['x'], contour['y']))
     83    fid.write('\n')
  • issm/trunk/src/m/exp/operation/exp_ginput.m

    r24313 r27035  
    55%      [xi yi] = exp_ginput(numclicks,options);
    66
    7 
    8 ginputtype = getfieldvalue(options,'ginputtype','default');
     7%ginputtype = getfieldvalue(options,'ginputtype','default');
    98ginputtype = getfieldvalue(options,'ginputtype','myginput');
    109
     
    1716                error('not supported yet');
    1817end
    19 
    20 
  • issm/trunk/src/m/geometry/VolumeAboveFloatation.m

    r25836 r27035  
    1 function V = VolumeAboveFloatation(md)
     1function V = VolumeAboveFloatation(md,step,flags)
    22%VOLUMEABOVEFLOATATION - returns volume above floatation
    33%
    44%   Usage:
    5 %      V = VolumeAboveFloatation(md)
     5%      V = VolumeAboveFloatation(md)          % uses model fiels alone
     6%      V = VolumeAboveFloatation(md,10)       % Will look at step 10 of transient solution
     7%      V = VolumeAboveFloatation(md,10,flags) % Will look at step 10 of transient solution, only flaged elements
    68
    79%Special case if 3d
     
    1719        error('not supported yet');
    1820end
     21
    1922%1. get some parameters
    2023rho_ice   = md.materials.rho_ice;
     
    2225
    2326%2. compute averages
    24 base        = mean(md.geometry.base(index),2);
    25 surface     = mean(md.geometry.surface(index),2);
    26 bathymetry  = mean(md.geometry.bed(index),2);
     27if nargin==1
     28        base           = mean(md.geometry.base(index),2);
     29        surface        = mean(md.geometry.surface(index),2);
     30        bathymetry     = mean(md.geometry.bed(index),2);
     31        ice_levelset   = md.mask.ice_levelset;
     32        ocean_levelset = md.mask.ocean_levelset;
     33else
     34        if isprop(md.results.TransientSolution(step),'MaskIceLevelset')
     35                ice_levelset   = md.results.TransientSolution(step).MaskIceLevelset;
     36        else
     37                ice_levelset   = md.mask.ice_levelset;
     38        end
     39   ocean_levelset = md.results.TransientSolution(step).MaskOceanLevelset;
     40   base           = mean(md.results.TransientSolution(step).Base(index),2);
     41   surface        = mean(md.results.TransientSolution(step).Surface(index),2);
     42        if isprop(md.results.TransientSolution(step),'Bed')
     43                bathymetry  = mean(md.results.TransientSolution(step).Bed(index),2);
     44        else
     45                 bathymetry  = mean(md.geometry.bed(index),2);
     46         end
     47end
    2748
    2849%3. get areas of all triangles
     
    3354
    3455%5. take out the ones that are outside of levelset or floating
    35 pos = find(min(md.mask.ice_levelset(index),[],2)>0 | min(md.mask.ocean_levelset(index),[],2)<0);
     56pos = find(min(ice_levelset(index),[],2)>0 | min(ocean_levelset(index),[],2)<0);
    3657V(pos) = 0;
     58
     59%In case we are only looking at one portion of the domain...
     60if nargin==3
     61        V(find(~flags)) = 0;
     62end
    3763
    3864%sum individual contributions
  • issm/trunk/src/m/inversions/marshallcostfunctions.py

    r24313 r27035  
    1414              505: 'ThicknessAcrossGradient'}
    1515
    16     data = [cfDict[cf] for cf in cost_functions]
     16    if type(cost_functions) == int:
     17        data = [cfDict[cost_functions]]
     18    else:
     19        data = [cfDict[cf] for cf in cost_functions]
    1720    #  #copy list first
    1821    # data = copy.deepcopy(cost_functions)
  • issm/trunk/src/m/io/loadmodel.py

    r25836 r27035  
    99
    1010
    11 def loadmodel(path, onlylast=False):
     11def loadmodel(path, singletime=None, singleres=None):
    1212    """LOADMODEL - load a model
    1313
     
    3131    #       try:
    3232    #recover model on file and name it md
    33     struc = loadvars(path, onlylast=onlylast)
     33    struc = loadvars(path, singletime=singletime, singleres=singleres)
    3434    name = [key for key in list(struc.keys())]
    3535    if len(name) > 1:
  • issm/trunk/src/m/io/loadvars.py

    r26744 r27035  
    77from re import findall, split
    88import shelve
    9 from netCDF4 import Dataset
     9from netCDF4 import Dataset, chartostring
    1010import numpy as np
     11import numpy.ma as ma
     12from importlib import import_module
    1113from model import *
    1214
     
    3032    filename = ''
    3133    nvdict = {}
    32     debug = False  #print messages if true
     34    verbose = 0  # 0 for silent 5 for chatty
    3335
    3436    if len(args) >= 1 and isinstance(args[0], str):
     
    5254        raise TypeError("Unrecognized input arguments.")
    5355
    54     onlylast = False
     56    timeindex = False
    5557
    5658    for key, value in kwargs.items():
    57         if key == 'onlylast':
    58             onlylast = value
     59        if key == 'singletime':
     60            timeindex = value
     61        if key == 'singleres':
     62            resname = value
    5963
    6064    if whichdb(filename):   #We used python pickle for the save
     
    8791        for mod in dict.keys(classtype):
    8892            #==== First we create the model structure  {{{
    89             if debug:
     93            if verbose > 0:
    9094                print(' ==== Now treating classtype {}'.format(mod))
    9195            if mod not in classtree.keys():
     
    9498                # this points to a subclass (results.TransientSolution for example)
    9599                curclass = NCFile.groups[classtree[mod][0]].groups[classtree[mod][1]]
    96                 if debug:
     100                if verbose > 0:
    97101                    print("    ==> {} is of class {}".format(mod, classtype[mod]))
    98102                if classtype[mod][0] == 'results.solutionstep':  #Treating results {{{
     
    100104                    #that is the current treatment
    101105                    #here we have a more NC approach with time being a dimension
    102                     listtype = split(r'\.', classtype[mod][0])[0]
     106                    listtype = split(r'\.', classtype[mod][0])[1]
     107                    print(listtype)
    103108                    if len(NCFile.dimensions['Time']) == 1:
    104109                        nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = getattr(classtype[mod][1], listtype)()
     
    106111                    else:
    107112                        #Time dimension is in all the variables so we take that as stepnumber for the results
    108                         if onlylast:   #we load only the last result to save on time and memory
     113                        if timeindex:   #we load only the last result to save on time and memory
    109114                            nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = [getattr(classtype[mod][1], listtype)()]
    110115                            Tree = nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]]
     
    126131                        Tree = nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]]
    127132                    else:
    128                         if onlylast:   #we load only the last result to save on time and memory
     133                        if timeindex:   #we load only the last result to save on time and memory
    129134                            nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = [getattr(classtype[mod][1], listtype)()]
    130135                            Tree = nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]]
    131136                        else:
    132                             #nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = [getattr(classtype[mod][1], listtype)() for i in range(max(1, len(NCFile.dimensions['Time'])))]
    133                             #Tree = nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]][:]
    134137                            setattr(nvdict['md'].__dict__[classtree[mod][0]], classtree[mod][1], getattr(classtype[mod][1], 'solution')([]))
    135138                            for i in range(max(1, stepnum)):
     
    137140                            Tree = nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]][:]
    138141                    #}}}
    139                 elif classtype[mod][0] == 'massfluxatgate':  #this is for output definitions {{{
     142                #elif classtype[mod][0] == 'massfluxatgate.massfluxatgate':  #this is for output definitions {{{
     143                elif mod.startswith('outputdefinition'):  #this is for output definitions {{{
    140144                    defname = split('Output|[0-9]+', classtree[mod][1])[1] + 's'
    141145                    defindex = int(findall('[0-9]+', classtree[mod][1])[0])
    142                     nvdict['md'].__dict__[classtree[mod][0]].__dict__[defname].append(getattr(classtype[mod][1], classtype[mod][0])())
     146                    outdeftype = split(r'\.', classtype[mod][0])[0]
     147                    nvdict['md'].__dict__[classtree[mod][0]].__dict__[defname].append(getattr(classtype[mod][1], outdeftype)())
    143148                    Tree = nvdict['md'].__dict__[classtree[mod][0]].__dict__[defname][defindex - 1]
    144149                #}}}
    145150                else:
    146                     if debug:
     151                    if verbose > 0:
    147152                        print("    Using the default for md.{}.{}, is that right??".format(classtree[mod][0], classtree[mod][1]))
    148153                    try:
    149154                        modulename = split(r'\.', classtype[mod][0])[0]
    150                         if debug:
     155                        if verbose > 0:
    151156                            print("    trying to import {} from {}".format(classtype[mod][0], modulename))
    152157                        nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = getattr(classtype[mod][1], modulename)()
     
    154159                        print("WARNING: md.{}.{} is not initialized, hopefully that was done in the main group:".format(classtree[mod][0], classtree[mod][1]))
    155160                    Tree = nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]]
     161            elif classtype[mod][0] == 'SMBgemb.SMBgemb':
     162                curclass = NCFile.groups[classtree[mod][0]]
     163                modulename = split(r'\.', classtype[mod][0])[0]
     164                nvdict['md'].__dict__[mod] = getattr(classtype[mod][1], modulename)(nvdict['md'].__dict__['mesh'], nvdict['md'].__dict__['geometry'])
     165                Tree = nvdict['md'].__dict__[classtree[mod][0]]
    156166            else:
    157167                curclass = NCFile.groups[classtree[mod][0]]
     
    159169                nvdict['md'].__dict__[mod] = getattr(classtype[mod][1], modulename)()
    160170                Tree = nvdict['md'].__dict__[classtree[mod][0]]
    161             if debug:
     171            if verbose > 0:
    162172                print("    for {} Tree is a {} with len {}".format(mod, Tree.__class__.__name__, len(curclass.groups)))
    163173            # }}}
     
    165175            #for i in range(0, max(1, len(curclass.groups))):
    166176            if len(curclass.groups) > 0:  #that is presumably only for old style NC where each result step had its own group
    167                 if onlylast:
    168                     groupclass = [curclass.groups[keylist[len(curclass.groups) - 1]]]
     177                if timeindex:
     178                    if timeindex < 0:
     179                        groupclass = [curclass.groups[keylist[len(curclass.groups) - timeindex]]]
     180                    else:
     181                        groupclass = [curclass.groups[keylist[timeindex]]]
    169182                else:
    170183                    groupclass = [curclass.groups[key] for key in keylist]
     
    174187            for groupindex, listclass in enumerate(groupclass):
    175188                for var in listclass.variables:
    176                     if var not in ['errlog', 'outlog']:
    177                         varval = listclass.variables[str(var)]
    178                         vardim = varval.ndim
    179                         if debug:
    180                             print("    ==> treating var {} of dimension {}".format(var, vardim))
    181                         #There is a special treatment for results to account for its specific structure
    182                         #that is the new export version where time is a named dimension
    183                         NewFormat = 'Time' in NCFile.dimensions
    184                         if type(Tree) == list:  # and NewFormat:
    185                             if onlylast:
    186                                 if NewFormat:
    187                                     if vardim == 1:
    188                                         Tree[0].__dict__[str(var)] = varval[-1].data
    189                                     elif vardim == 2:
    190                                         Tree[0].__dict__[str(var)] = varval[-1, :].data
    191                                     elif vardim == 3:
    192                                         Tree[0].__dict__[str(var)] = varval[-1, :, :].data
     189                    if not resname or var == resname:
     190                        if var not in ['errlog', 'outlog']:
     191                            varval = listclass.variables[str(var)]
     192                            vardim = varval.ndim
     193                            if verbose > 0:
     194                                print("    ==> treating var {} of dimension {}".format(var, vardim))
     195                            #There is a special treatment for results to account for its specific structure
     196                            #that is the new export version where time is a named dimension
     197                            NewFormat = 'Time' in NCFile.dimensions
     198                            if type(Tree) == list:  # and NewFormat:
     199                                if timeindex:
     200                                    if NewFormat:
     201                                        if vardim == 0:
     202                                            try:
     203                                                Tree[0].__dict__[str(var)] = varval[timeindex].data
     204                                            except IndexError:
     205                                                print('WARNING: No data on index {} for {} reverting to last time.'.format(timeindex, str(var)))
     206                                                Tree[0].__dict__[str(var)] = varval[-1].data
     207                                        elif vardim == 1:
     208                                            try:
     209                                                Tree[0].__dict__[str(var)] = varval[timeindex].data
     210                                            except IndexError:
     211                                                print('WARNING: No data on index {} for {} reverting to last time.'.format(timeindex, str(var)))
     212                                                Tree[0].__dict__[str(var)] = varval[-1].data
     213                                        elif vardim == 2:
     214                                            Tree[0].__dict__[str(var)] = varval[timeindex, :].data
     215                                        elif vardim == 3:
     216                                            Tree[0].__dict__[str(var)] = varval[timeindex, :, :].data
     217                                        else:
     218                                            print('table dimension greater than 3 not implemented yet')
     219                                    else:  #old format had step sorted in difeerent group so last group is last time
     220                                        Tree[0].__dict__[str(var)] = varval[:].data
     221                                else:
     222                                    if NewFormat:
     223                                        incomplete = 'Time' not in varval.dimensions
     224                                        if incomplete:
     225                                            try:
     226                                                chosendim = varval.dimensions[0]
     227                                                timelist = np.arange(0, len(NCFile.dimensions[chosendim]))
     228                                                print('WARNING, {} is not present on every times, we chose {}({}) as the dimension to write it with'.format(var, chosendim, len(NCFile.dimensions[chosendim])))
     229                                            except IndexError:
     230                                                #just one step, so no dimension, we just put it on the first solutionstep
     231                                                timelist = [0]
     232                                        else:
     233                                            timelist = np.arange(0, len(NCFile.dimensions['Time']))
     234                                        for t in timelist:
     235                                            if verbose > 5:
     236                                                print("filing step {} for {}".format(t, var))
     237                                            if vardim == 0:
     238                                                Tree[t].__dict__[str(var)] = varval[:].data
     239                                            elif vardim == 1:
     240                                                stepval = ma.masked_array(varval[t].data, mask=np.where(np.isnan(varval[t]), 1, 0))
     241                                                Tree[t].__dict__[str(var)] = ma.compressed(stepval)
     242                                            elif vardim == 2:
     243                                                stepval = ma.masked_array(varval[t, :].data, mask=np.where(np.isnan(varval[t, :]), 1, 0))
     244                                                Tree[t].__dict__[str(var)] = ma.compressed(stepval)
     245                                            elif vardim == 3:
     246                                                stepval = ma.masked_array(varval[t, :, :].data, mask=np.where(np.isnan(varval[t, :, :]), 1, 0))
     247                                                Tree[t].__dict__[str(var)] = ma.compressed(stepval).reshape((stepval.count(0)[0], stepval.count(1)[0]))
     248                                            else:
     249                                                print('table dimension greater than 3 not implemented yet')
    193250                                    else:
    194                                         print('table dimension greater than 3 not implemented yet')
    195                                 else:  #old format had step sorted in difeerent group so last group is last time
    196                                     Tree[0].__dict__[str(var)] = varval[:].data
     251                                        if verbose > 0:
     252                                            print("filing step {} for {}".format(groupindex, var))
     253                                        Tree[groupindex].__dict__[str(var)] = varval[:].data
    197254                            else:
    198                                 if NewFormat:
    199                                     incomplete = 'Time' not in varval.dimensions and NewFormat
    200                                     if incomplete:
    201                                         chosendim = varval.dimensions[0]
    202                                         timelist = np.arange(0, len(NCFile.dimensions[chosendim]))
    203                                         print('WARNING, {} is not present on every times, we chose {}({}) as the dimension to write it with'.format(var, chosendim, len(NCFile.dimensions[chosendim])))
     255                                if vardim == 0:  #that is a scalar
     256                                    if str(varval[0]) in ['', '--', 'emptycell']:  #no value
     257                                        Tree.__dict__[str(var)] = []
     258                                    elif varval[0] == 'True':  #treatin bool
     259                                        Tree.__dict__[str(var)] = True
     260                                    elif varval[0] == 'False':  #treatin bool
     261                                        Tree.__dict__[str(var)] = False
    204262                                    else:
    205                                         timelist = np.arange(0, len(NCFile.dimensions['Time']))
    206                                     for t in timelist:
    207                                         if debug:
    208                                             print("filing step {} for {}".format(t, var))
    209                                         if vardim == 0:
    210                                             Tree[t].__dict__[str(var)] = varval[:].data
    211                                         elif vardim == 1:
    212                                             Tree[t].__dict__[str(var)] = varval[t].data
    213                                         elif vardim == 2:
    214                                             Tree[t].__dict__[str(var)] = varval[t, :].data
    215                                         elif vardim == 3:
    216                                             Tree[t].__dict__[str(var)] = varval[t, :, :].data
    217                                         else:
    218                                             print('table dimension greater than 3 not implemented yet')
     263                                        Tree.__dict__[str(var)] = varval[0].item()
     264
     265                                elif vardim == 1:  #that is a vector
     266                                    if verbose > 0:
     267                                        print("   for variable {} type is {}".format(str(var), varval.dtype))
     268                                    if varval.dtype == str:
     269                                        if varval.shape[0] == 1:
     270                                            Tree.__dict__[str(var)] = [str(varval[0]), ]
     271                                        elif 'True' in varval[:] or 'False' in varval[:]:
     272                                            Tree.__dict__[str(var)] = np.asarray([V == 'True' for V in varval[:]], dtype=bool)
     273                                        else:
     274                                            Tree.__dict__[str(var)] = [str(vallue) for vallue in varval[:]]
     275                                    elif varval.dtype == "|S1":  #that is for matlab chararcter arrays
     276                                        stringlist = chartostring(varval[:])
     277                                        Tree.__dict__[str(var)] = [stringlist.tolist(), ]
     278                                    else:
     279                                        try:
     280                                            #some thing specifically require a list
     281                                            mdtype = type(Tree.__dict__[str(var)])
     282                                        except KeyError:
     283                                            mdtype = float
     284                                        if mdtype == list:
     285                                            Tree.__dict__[str(var)] = [mdval for mdval in varval[:]]
     286                                        else:
     287                                            Tree.__dict__[str(var)] = varval[:].data
     288
     289                                elif vardim == 2:
     290                                    #dealling with dict
     291                                    if verbose > 0:
     292                                        print("   for variable {} type is {}".format(str(var), varval.dtype))
     293                                    if varval.dtype == str:  #that is for dictionaries
     294                                        if any(varval[:, 0] == 'toolkit'):  #toolkit definition have to be first
     295                                            Tree.__dict__[str(var)] = OrderedDict([('toolkit', str(varval[np.where(varval[:, 0] == 'toolkit')[0][0], 1]))])
     296                                            strings1 = [str(arg[0]) for arg in varval if arg[0] != 'toolkits']
     297                                            strings2 = [str(arg[1]) for arg in varval if arg[0] != 'toolkits']
     298                                            Tree.__dict__[str(var)].update(list(zip(strings1, strings2)))
     299                                        else:
     300                                            strings1 = [str(arg[0]) for arg in varval]
     301                                            strings2 = [str(arg[1]) for arg in varval]
     302                                            Tree.__dict__[str(var)] = OrderedDict(list(zip(strings1, strings2)))
     303                                    elif varval.dtype == "|S1":  #that is for matlab chararcter arrays
     304                                        stringlist = chartostring(varval[:, :])
     305                                        stringlist = [string.strip() for string in stringlist]
     306                                        Tree.__dict__[str(var)] = stringlist
     307                                    else:
     308                                        if type(Tree) == list:
     309                                            t = indexlist[i]
     310                                            if listtype == 'dict':
     311                                                Tree[t][str(var)] = varval[:, :].data
     312                                            else:
     313                                                Tree[t].__dict__[str(var)] = varval[:, :].data
     314                                        else:
     315                                            Tree.__dict__[str(var)] = varval[:, :].data
     316                                elif vardim == 3:
     317                                    Tree.__dict__[str(var)] = varval[:, :, :].data
    219318                                else:
    220                                     if debug:
    221                                         print("filing step {} for {}".format(groupindex, var))
    222                                     Tree[groupindex].__dict__[str(var)] = varval[:].data
    223                         else:
    224                             if vardim == 0:  #that is a scalar
    225                                 if str(varval[0]) == '':  #no value
    226                                     Tree.__dict__[str(var)] = []
    227                                 elif varval[0] == 'True':  #treatin bool
    228                                     Tree.__dict__[str(var)] = True
    229                                 elif varval[0] == 'False':  #treatin bool
    230                                     Tree.__dict__[str(var)] = False
    231                                 else:
    232                                     Tree.__dict__[str(var)] = varval[0].item()
    233 
    234                             elif vardim == 1:  #that is a vector
    235                                 if varval.dtype == str:
    236                                     if varval.shape[0] == 1:
    237                                         Tree.__dict__[str(var)] = [str(varval[0]), ]
    238                                     elif 'True' in varval[:] or 'False' in varval[:]:
    239                                         Tree.__dict__[str(var)] = np.asarray([V == 'True' for V in varval[:]], dtype=bool)
    240                                     else:
    241                                         Tree.__dict__[str(var)] = [str(vallue) for vallue in varval[:]]
    242                                 else:
    243                                     try:
    244                                         #some thing specifically require a list
    245                                         mdtype = type(Tree.__dict__[str(var)])
    246                                     except KeyError:
    247                                         mdtype = float
    248                                     if mdtype == list:
    249                                         Tree.__dict__[str(var)] = [mdval for mdval in varval[:]]
    250                                     else:
    251                                         Tree.__dict__[str(var)] = varval[:].data
    252 
    253                             elif vardim == 2:
    254                                 #dealling with dict
    255                                 if varval.dtype == str:  #that is for dictionaries
    256                                     if any(varval[:, 0] == 'toolkit'):  #toolkit definition have to be first
    257                                         Tree.__dict__[str(var)] = OrderedDict([('toolkit', str(varval[np.where(varval[:, 0] == 'toolkit')[0][0], 1]))])
    258                                         strings1 = [str(arg[0]) for arg in varval if arg[0] != 'toolkits']
    259                                         strings2 = [str(arg[1]) for arg in varval if arg[0] != 'toolkits']
    260                                         Tree.__dict__[str(var)].update(list(zip(strings1, strings2)))
    261                                     else:
    262                                         strings1 = [str(arg[0]) for arg in varval]
    263                                         strings2 = [str(arg[1]) for arg in varval]
    264                                         Tree.__dict__[str(var)] = OrderedDict(list(zip(strings1, strings2)))
    265                                 else:
    266                                     if type(Tree) == list:
    267                                         t = indexlist[i]
    268                                         if listtype == 'dict':
    269                                             Tree[t][str(var)] = varval[:, :].data
    270                                         else:
    271                                             Tree[t].__dict__[str(var)] = varval[:, :].data
    272                                     else:
    273                                         Tree.__dict__[str(var)] = varval[:, :].data
    274                             elif vardim == 3:
    275                                 Tree.__dict__[str(var)] = varval[:, :, :].data
    276                             else:
    277                                 print('table dimension greater than 3 not implemented yet')
     319                                    print('table dimension greater than 3 not implemented yet')
    278320                # }}}
    279321                #==== And with atribute {{{
    280322                for attr in listclass.ncattrs():
    281                     if debug:
     323                    if verbose > 0:
    282324                        print("      ==> treating attribute {}".format(attr))
    283325                    if attr != 'classtype':  #classtype is for treatment, don't get it back
    284                         attribute = str(attr).swapcase()  #there is a reason for swapcase, no sure what it isanymore
    285                         if attr == 'VARNAME':
     326                        if attr == 'varname':
    286327                            attribute = 'name'
     328                        else:
     329                            attribute = attr
    287330                        if type(Tree) == list:
    288                             if debug:
     331                            if verbose > 0:
    289332                                print("        printing with index 0")
    290333                            if listtype == 'dict':
     
    293336                                Tree[0].__dict__[attribute] = str(listclass.getncattr(attr))
    294337                        else:
    295                             Tree.__dict__[attribute] = str(listclass.getncattr(attr))
    296338                            if listclass.getncattr(attr) == 'True':
    297339                                Tree.__dict__[attribute] = True
    298340                            elif listclass.getncattr(attr) == 'False':
    299341                                Tree.__dict__[attribute] = False
     342                            elif listclass.getncattr(attr) == 'emptycell':
     343                                Tree.__dict__[attribute] = []
     344                            else:
     345                                Tree.__dict__[attribute] = str(listclass.getncattr(attr))
    300346                # }}}
    301347            # }}}
     
    328374                    try:
    329375                        modulename = split(r'\.', class_dict[classe][0])[0]
    330                         class_dict[classe].append(__import__(modulename))
     376                        class_dict[classe].append(import_module(modulename))
    331377                    except ModuleNotFoundError:
    332378                        #submodule probably has a different name
    333379                        modulename = str(getattr(NCData.groups[group].groups[subgroup], 'classtype'))
    334380                        print("WARNING importing {} rather than {}".format(modulename, class_dict[classe][0]))
    335                         class_dict[classe].append(__import__(modulename))
     381                        class_dict[classe].append(import_module(modulename))
    336382                class_tree[classe] = [group, subgroup]
    337383        else:
     
    344390                        print("WARNING: module {} does not exist anymore and is skipped".format(modulename))
    345391                    else:
    346                         class_dict[classe].append(__import__(modulename))
     392                        class_dict[classe].append(import_module(modulename))
    347393                        class_tree[classe] = [group, ]
    348394            except AttributeError:
  • issm/trunk/src/m/mesh/meshconvert.m

    r17806 r27035  
    4040md.mesh.numberofedges    = size(md.mesh.edges,1);
    4141md.mesh.vertexonboundary = zeros(md.mesh.numberofvertices,1); md.mesh.vertexonboundary(md.mesh.segments(:,1:2)) = 1;
     42md.mesh.elementconnectivity=md.private.bamg.mesh.ElementConnectivity;
     43md.mesh.elementconnectivity(find(isnan(md.mesh.elementconnectivity)))=0;
  • issm/trunk/src/m/mesh/roundmesh.m

    r22758 r27035  
    1 function md=roundmesh(md,radius,resolution)
     1function md=roundmesh(md,radius,resolution,varargin)
    22%ROUNDMESH - create an unstructured round mesh
    33%
     
    88%   Usage:
    99%      md=roundmesh(md,radius,resolution)
     10%      md=roundmesh(md,radius,resolution,'domain.exp')
    1011
    1112%First we have to create the domain outline
    12 expname = [tempname() '.exp'];
     13if nargin<4
     14        expname = [tempname() '.exp'];
     15else
     16        expname = varargin{1};
     17end
    1318
    1419%Get number of points on the circle
     
    3237
    3338%delete domain
    34 delete(expname);
     39if nargin<4
     40        delete(expname);
     41end
    3542end
    3643
  • issm/trunk/src/m/mesh/roundmesh.py

    r24686 r27035  
    2626    y_list = roundsigfig(radius * np.sin(theta), 12)
    2727    A = OrderedDict()
    28     A['x'] = [x_list]
    29     A['y'] = [y_list]
     28    A['x'] = x_list
     29    A['y'] = y_list
    3030    A['density'] = 1.
    3131    expwrite(A, 'RoundDomainOutline.exp')
  • issm/trunk/src/m/miscellaneous/MatlabFuncs.py

    r26744 r27035  
    22functions of the same, respective name.
    33
    4 Where possible, users are encouraged to use native and/or the most efficient 
    5 methods in Python, but we provide these functions as a way to make translations 
     4Where possible, users are encouraged to use native and/or the most efficient
     5methods in Python, but we provide these functions as a way to make translations
    66from the MATLAB to the Python ISSM API more seamless.
    77"""
     
    8282
    8383def cosdsingle(x):  # {{{
    84     """function cosdsingle - Helper function for cosd to reduce repetition of 
     84    """function cosdsingle - Helper function for cosd to reduce repetition of
    8585    logic
    8686
     
    162162    NOTE:
    163163    - Only the following functionality is currently implemented:
    164         - C = intersect(A,B) returns the data common to both A and B, with no 
     164        - C = intersect(A,B) returns the data common to both A and B, with no
    165165        repetitions. C is in sorted order.
    166166
     
    175175
    176176    NOTE:
    177     - Takes a type as its second argument (in contrast to the MATLAB function 
     177    - Takes a type as its second argument (in contrast to the MATLAB function
    178178    that it replicates, which takes a string representing the name of a type)
    179179    """
     
    204204def ismember(a, s):  # {{{
    205205    import numpy as np
    206 
    207206    if not isinstance(s, (tuple, list, dict, np.ndarray)):
    208207        s = [s]
     
    215214    else:
    216215        if not isinstance(s, np.ndarray):
    217             b = np.empty_like(a)
     216            b = np.empty_like(a).flat
    218217            for i, item in enumerate(a.flat):
    219                 b.flat[i] = item in s
     218                b[i] = item in s
    220219        else:
    221220            b = np.in1d(a.flat, s.flat).reshape(a.shape)
    222 
    223221    return b
    224222# }}}
     
    272270def oshostname():  # {{{
    273271    import socket
    274 
    275     return socket.gethostname()
     272    hostname = socket.gethostname()
     273
     274    return hostname.lower()
    276275# }}}
    277276
     
    298297
    299298def sindsingle(x):  # {{{
    300     """function sindsingle - Helper function for sind to reduce repetition of 
     299    """function sindsingle - Helper function for sind to reduce repetition of
    301300    logic
    302301
  • issm/trunk/src/m/miscellaneous/diagnostics.m

    r25836 r27035  
    3535        %grounding line :
    3636        if getfieldvalue(options,'gl',0),
    37                 contours=contourlevelzero(md,md.mask.ocean_levelset,0);
     37                contours=isoline(md,md.mask.ocean_levelset);
    3838                expwrite(contours,[path '/groundingline.exp']);
    3939                exp2shp([path '/groundingline.shp'],[path '/groundingline.exp']);
  • issm/trunk/src/m/miscellaneous/fielddisplay.py

    r25836 r27035  
    110110
    111111
    112 def displayunit(offset, name, characterization, comment): #{{{
     112def displayunit(offset, name, characterization, comment):  #{{{
    113113    #take care of name
    114114    if len(name) > 23:
     
    116116
    117117    #take care of characterization
    118     if m.strcmp(characterization, "''") or m.strcmp(characterization, '""') or m.strcmpi(characterization, 'nan'):
     118    if characterization in ["''", '""', 'nan', np.nan, 'NaN', "[0x1]"]:
    119119        characterization = "N/A"
    120120
  • issm/trunk/src/m/modules/CoordTransform.m

    r26744 r27035  
    44%   Usage:
    55%      [xout,yout] = CoordTransform(xin,yin,projin,projout)
    6 %
    7 %   xin,  yin : input coordinates
    8 %   xout, yout: output coordinates (in new projection)
    9 %   projin,projout: input/output projection string (PROJ)
     6%      - xin,  yin : input coordinates
     7%      - xout, yout: output coordinates (in new projection)
     8%      - projin,projout: input/output projection string (PROJ)
     9%   
     10%   Examples:
     11%      [md.mesh.lat md.mesh.long] = CoordTransform(md.mesh.x,  md.mesh.y,   'EPSG:3413','EPSG:4326');
     12%      [md.mesh.x   md.mesh.y]    = CoordTransform(md.mesh.lat,md.mesh.long,'EPSG:4326','EPSG:3413');
    1013%
    1114%   Example of Projections:
     15%      lat/lon    = 'EPSG:4326'  or  lat/lon = '+proj=longlat +datum=WGS84'
     16%      Greenland  = 'EPSG:3413' (polar stereographic 70N 45W)
     17%      Antarctica = 'EPSG:3031' (polar stereographic 71S 0E)
     18%     
     19%   ll2xy previous default equivalent (uses with Hugues Ellispoid S)
     20%      Greenland  = '+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +a=6378273 +b=6356889.448564109 +units=m +no_defs'
     21%      Antarctica = '+proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6378273 +b=6356889.448564109 +units=m +no_defs'
     22%      Bamber Greenland = '+proj=stere +lat_0=90 +lat_ts=71 +lon_0=-39 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs'
    1223%
    13 %   lat/lon = '+init=epsg:4326'
    14 %   lat/lon = '+proj=longlat +datum=WGS84'
    15 %
    16 %   ll2xy default equivalent (uses with Hugues Ellispoid S)
    17 %   Greenland = '+proj=stere +lat_0=90 +lat_ts=70 +lon_0=-45 +k=1 +x_0=0 +y_0=0 +a=6378273 +b=6356889.448564109 +units=m +no_defs'
    18 %   Antarctica = '+proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +a=6378273 +b=6356889.448564109 +units=m +no_defs'
    19 %   Bamber Greenland = '+proj=stere +lat_0=90 +lat_ts=71 +lon_0=-39 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs'
    20 %
    21 %   For latitude/longitude, x is longitude and y latitude and the angles are in
    22 %   rad
    23 %
    24 %   This function will only work if PROJ has been installed and --with-proj-dir
     24%   This function will only work if PROJ has been installed and --with-proj-dir
    2525%   option has been set to its location in ISSM configuration
    2626
  • issm/trunk/src/m/os/issmscpin.py

    r26744 r27035  
    2222            pass
    2323    #if hostname and host are the same, do a simple copy
    24     if hostname == host:
     24    if strcmpi(hostname, host):  #hostname == host:
    2525        for package in packages:
    2626            try:
  • issm/trunk/src/m/os/issmscpout.py

    r26744 r27035  
    11import os
    2 from socket import gethostname
    32import subprocess
    43from MatlabFuncs import *
     
    1716    #if hostname and host are the same, do a simple copy
    1817
    19     if host == hostname:
     18    if strcmpi(host, hostname):  #host == hostname:
    2019        for package in packages:
    2120            here = os.getcwd()
  • issm/trunk/src/m/os/issmssh.py

    r26744 r27035  
    3737                subprocess.call('ssh -l %s -p %d localhost "%s"' % (login, port, command), shell=True)
    3838            else:
    39                 subprocess.call('ssh -l %s %s "%s"' % (login, host, command), shell=True)
     39                subprocess.call('ssh -l {} {} "{}"'.format(login, host, command), shell=True)
    4040
    4141    # The following code was added to fix:
  • issm/trunk/src/m/parameterization/killberg.m

    r25836 r27035  
    2525%do not go through elements that are grounded, mark flag as 1 (done) need at least 2 vertices!
    2626%and initialize mask as 1 for all vertices of these elements
    27 isgrounded=(sum(md.mask.ocean_levelset(md.mesh.elements)>0,2)>1);
     27isgrounded=(sum(md.mask.ocean_levelset(md.mesh.elements)>0,2)>2);
    2828%isgrounded = max(md.mask.ocean_levelset(md.mesh.elements),[],2)>0;
    2929pos = find(isgrounded);
    30 element_flag(pos) = 1;
     30%element_flag(pos) = 1;
    3131mask(md.mesh.elements(pos,:)) = 1;
     32mask(md.mask.ice_levelset>=0) = 0;
    3233
    3334iter = 1;
  • issm/trunk/src/m/parameterization/reinitializelevelset.m

    r24686 r27035  
    1515
    1616%First: extract segments
    17 contours=contourlevelzero(md,levelset,0);
     17contours=isoline(md,levelset,'value',0);
    1818
    1919%Now, make this a distance field (might not be closed)
  • issm/trunk/src/m/parameterization/setflowequation.js

    r25836 r27035  
    33//
    44//   This routine works like plotmodel: it works with an even number of inputs
    5 //   'SIA','SSA','L1L2','MLHO','HO','FS' and 'fill' are the possible options
     5//   'SIA','SSA','L1L2','MOLHO','HO','FS' and 'fill' are the possible options
    66//   that must be followed by the corresponding exp file or flags list
    77//   It can either be a domain file (argus type, .exp extension), or an array of element flags.
     
    1111//   a string 'all' will be considered as the entire domain
    1212//   You can specify the type of coupling, 'penalties' or 'tiling', to use with the input 'coupling'
    13 //   NB: L1L2 and MLHO cannot currently be coupled to any other ice flow model
     13//   NB: L1L2 and MOLHO cannot currently be coupled to any other ice flow model
    1414//
    1515//   Usage:
     
    3838        HOflag   = FlagElements(md,options.getfieldvalue('HO',''));
    3939        L1L2flag = FlagElements(md,options.getfieldvalue('L1L2',''));
    40         MLHOflag = FlagElements(md,options.getfieldvalue('MLHO',''));
     40        MOLHOflag = FlagElements(md,options.getfieldvalue('MOLHO',''));
    4141        FSflag   = FlagElements(md,options.getfieldvalue('FS',''));
    4242        filltype = options.getfieldvalue('fill','none');
     
    5555
    5656        //check that each element has at least one flag
    57         for(var i=0;i<md.mesh.numberofelements;i++)if((SIAflag[i] + SSAflag[i] + HOflag[i] + L1L2flag[i] + MLHOflag[i] + FSflag[i])==0)
     57        for(var i=0;i<md.mesh.numberofelements;i++)if((SIAflag[i] + SSAflag[i] + HOflag[i] + L1L2flag[i] + MOLHOflag[i] + FSflag[i])==0)
    5858        throw Error("elements type not assigned, supported models are 'SIA','SSA','HO' and 'FS'");
    5959
    6060        //check that each element has only one flag
    61         if (ArrayAnyAboveStrict(ArrayXPY(SIAflag,SSAflag,HOflag,L1L2flag,MLHOflag),1)){
     61        if (ArrayAnyAboveStrict(ArrayXPY(SIAflag,SSAflag,HOflag,L1L2flag,MOLHOflag),1)){
    6262                console.log('setflowequation warning message: some elements have several types, higher order type is used for them')
    6363
     
    7171        //check that L1L2 is not coupled to any other model for now
    7272        if (ArrayAnyEqual(L1L2flag,1) & ArrayAnyEqual(ArrayOr(SIAflag,SSAflag,HOflag,FSflag),1)) throw Error('L1L2 cannot be coupled to any other model');
    73         if (ArrayAnyEqual(MLHOflag,1) & ArrayAnyEqual(ArrayOr(SIAflag,SSAflag,HOflag,FSflag),1)) throw Error('MLHO cannot be coupled to any other model');
     73        if (ArrayAnyEqual(MOLHOflag,1) & ArrayAnyEqual(ArrayOr(SIAflag,SSAflag,HOflag,FSflag),1)) throw Error('MOLHO cannot be coupled to any other model');
    7474
    7575        //Check that no HO or FS for 2d mesh
     
    100100        for(var i=0;i<pos.length;i++) for(var j=0;j<md.mesh.elements[0].length;j++) nodeonL1L2[md.mesh.elements[pos[i]][j]-1]=1;
    101101
    102         nodeonMLHO=NewArrayFill(md.mesh.numberofvertices,0);
    103         pos=ArrayFind(MLHOflag,1);
    104         for(var i=0;i<pos.length;i++) for(var j=0;j<md.mesh.elements[0].length;j++) nodeonMLHO[md.mesh.elements[pos[i]][j]-1]=1;
     102        nodeonMOLHO=NewArrayFill(md.mesh.numberofvertices,0);
     103        pos=ArrayFind(MOLHOflag,1);
     104        for(var i=0;i<pos.length;i++) for(var j=0;j<md.mesh.elements[0].length;j++) nodeonMOLHO[md.mesh.elements[pos[i]][j]-1]=1;
    105105
    106106        nodeonFS=NewArrayFill(md.mesh.numberofvertices,0);
     
    262262        pos=ArrayFind(SSAflag,1);for(var i=0;i<pos.length;i++)md.flowequation.element_equation[pos[i]]=2;
    263263        pos=ArrayFind(L1L2flag,1);for(var i=0;i<pos.length;i++)md.flowequation.element_equation[pos[i]]=3;
    264         pos=ArrayFind(MLHOflag,1);for(var i=0;i<pos.length;i++)md.flowequation.element_equation[pos[i]]=4;
     264        pos=ArrayFind(MOLHOflag,1);for(var i=0;i<pos.length;i++)md.flowequation.element_equation[pos[i]]=4;
    265265        pos=ArrayFind(HOflag,1);for(var i=0;i<pos.length;i++)md.flowequation.element_equation[pos[i]]=5;
    266266        pos=ArrayFind(FSflag,1);for(var i=0;i<pos.length;i++)md.flowequation.element_equation[pos[i]]=6;
     
    281281        pos=ArrayFind(nodeonSSA,1);for(var i=0;i<pos.length;i++)md.flowequation.vertex_equation[pos[i]]=2;
    282282        pos=ArrayFind(nodeonL1L2,1);for(var i=0;i<pos.length;i++)md.flowequation.vertex_equation[pos[i]]=3;
    283         pos=ArrayFind(nodeonMLHO,1);for(var i=0;i<pos.length;i++)md.flowequation.vertex_equation[pos[i]]=4;
     283        pos=ArrayFind(nodeonMOLHO,1);for(var i=0;i<pos.length;i++)md.flowequation.vertex_equation[pos[i]]=4;
    284284        pos=ArrayFind(nodeonHO,1);for(var i=0;i<pos.length;i++)md.flowequation.vertex_equation[pos[i]]=5;
    285285        pos=ArrayFind(nodeonFS,1);for(var i=0;i<pos.length;i++)md.flowequation.vertex_equation[pos[i]]=6;
     
    301301        md.flowequation.isSSA  = ArrayAnyEqual(md.flowequation.element_equation,2);
    302302        md.flowequation.isL1L2 = ArrayAnyEqual(md.flowequation.element_equation,3);
    303         md.flowequation.isMLHO = ArrayAnyEqual(md.flowequation.element_equation,4);
     303        md.flowequation.isMOLHO = ArrayAnyEqual(md.flowequation.element_equation,4);
    304304        md.flowequation.isHO   = ArrayAnyEqual(md.flowequation.element_equation,5);
    305305        md.flowequation.isFS   = ArrayAnyEqual(md.flowequation.element_equation,6);
  • issm/trunk/src/m/parameterization/setflowequation.m

    r26744 r27035  
    33%
    44%   This routine works like plotmodel: it works with an even number of inputs
    5 %   'SIA','SSA','L1L2','MLHO','HO','FS' and 'fill' are the possible options
     5%   'SIA','SSA','L1L2','MOLHO','HO','FS' and 'fill' are the possible options
    66%   that must be followed by the corresponding exp file or flags list
    77%   It can either be a domain file (argus type, .exp extension), or an array of element flags.
     
    1111%   a string 'all' will be considered as the entire domain
    1212%   You can specify the type of coupling, 'penalties' or 'tiling', to use with the input 'coupling'
    13 %   NB: L1L2 and MLHO cannot currently be coupled to any other ice flow model
     13%   NB: L1L2 and MOLHO cannot currently be coupled to any other ice flow model
    1414%
    1515%   Usage:
     
    3939HOflag   = FlagElements(md,getfieldvalue(options,'HO',''));
    4040L1L2flag = FlagElements(md,getfieldvalue(options,'L1L2',''));
    41 MLHOflag = FlagElements(md,getfieldvalue(options,'MLHO',''));
     41MOLHOflag = FlagElements(md,getfieldvalue(options,'MOLHO',''));
    4242FSflag   = FlagElements(md,getfieldvalue(options,'FS',''));
    4343filltype = getfieldvalue(options,'fill','none');
     
    5454
    5555%check that each element has at least one flag
    56 if any(SIAflag+SSAflag+HOflag+L1L2flag+MLHOflag+FSflag==0),
     56if any(SIAflag+SSAflag+HOflag+L1L2flag+MOLHOflag+FSflag==0),
    5757        error('elements type not assigned, supported models are ''SIA'',''SSA'',''HO'' and ''FS''')
    5858end
    5959
    6060%check that each element has only one flag
    61 if any(SIAflag+SSAflag+HOflag+L1L2flag+MLHOflag+FSflag>1),
     61if any(SIAflag+SSAflag+HOflag+L1L2flag+MOLHOflag+FSflag>1),
    6262        disp('setflowequation.m: Warning: some elements have several types, higher order type is used for them')
    6363        SIAflag(find(SIAflag & SSAflag))=0;
     
    7070        error('L1L2 cannot be coupled to any other model');
    7171end
    72 if any(MLHOflag) & any(SIAflag | SSAflag | HOflag | FSflag)
    73         error('MLHO cannot be coupled to any other model');
     72if any(MOLHOflag) & any(SIAflag | SSAflag | HOflag | FSflag)
     73        error('MOLHO cannot be coupled to any other model');
    7474end
    7575
     
    9191nodeonHO=zeros(md.mesh.numberofvertices,1);   nodeonHO(md.mesh.elements(find(HOflag),:))=1;
    9292nodeonL1L2=zeros(md.mesh.numberofvertices,1); nodeonL1L2(md.mesh.elements(find(L1L2flag),:))=1;
    93 nodeonMLHO=zeros(md.mesh.numberofvertices,1); nodeonMLHO(md.mesh.elements(find(MLHOflag),:))=1;
     93nodeonMOLHO=zeros(md.mesh.numberofvertices,1); nodeonMOLHO(md.mesh.elements(find(MOLHOflag),:))=1;
    9494nodeonFS=zeros(md.mesh.numberofvertices,1);
    9595noneflag=zeros(md.mesh.numberofelements,1);
     
    248248md.flowequation.element_equation(find(SSAflag))=2;
    249249md.flowequation.element_equation(find(L1L2flag))=3;
    250 md.flowequation.element_equation(find(MLHOflag))=4;
     250md.flowequation.element_equation(find(MOLHOflag))=4;
    251251md.flowequation.element_equation(find(HOflag))=5;
    252252md.flowequation.element_equation(find(FSflag))=6;
     
    264264pos=find(nodeonSSA);  md.flowequation.vertex_equation(pos)=2;
    265265pos=find(nodeonL1L2); md.flowequation.vertex_equation(pos)=3;
    266 pos=find(nodeonMLHO); md.flowequation.vertex_equation(pos)=4;
     266pos=find(nodeonMOLHO); md.flowequation.vertex_equation(pos)=4;
    267267pos=find(nodeonHO);   md.flowequation.vertex_equation(pos)=5;
    268268pos=find(nodeonFS);   md.flowequation.vertex_equation(pos)=6;
     
    287287md.flowequation.isSSA  = double(any(md.flowequation.element_equation == 2));
    288288md.flowequation.isL1L2 = double(any(md.flowequation.element_equation == 3));
    289 md.flowequation.isMLHO = double(any(md.flowequation.element_equation == 4));
     289md.flowequation.isMOLHO = double(any(md.flowequation.element_equation == 4));
    290290md.flowequation.isHO   = double(any(md.flowequation.element_equation == 5));
    291291md.flowequation.isFS   = double(any(md.flowequation.element_equation == 6));
  • issm/trunk/src/m/parameterization/setflowequation.py

    r26744 r27035  
    99
    1010    This routine works like plotmodel: it works with an even number of inputs
    11     'SIA', 'SSA', 'HO', 'L1L2', 'MLHO', 'FS' and 'fill' are the possible
     11    'SIA', 'SSA', 'HO', 'L1L2', 'MOLHO', 'FS' and 'fill' are the possible
    1212    options that must be followed by the corresponding exp file or flags list.
    1313    It can either be a domain file (argus type, .exp extension), or an array of
     
    4545    HOflag = FlagElements(md, options.getfieldvalue('HO', ''))
    4646    L1L2flag = FlagElements(md, options.getfieldvalue('L1L2', ''))
    47     MLHOflag = FlagElements(md, options.getfieldvalue('MLHO', ''))
     47    MOLHOflag = FlagElements(md, options.getfieldvalue('MOLHO', ''))
    4848    FSflag = FlagElements(md, options.getfieldvalue('FS', ''))
    4949    filltype = options.getfieldvalue('fill', 'none')
     
    5757        HOflag = ~SIAflag & ~SSAflag & ~FSflag
    5858    #check that each element has at least one flag
    59     if not any(SIAflag + SSAflag + L1L2flag + MLHOflag + HOflag + FSflag):
     59    if not any(SIAflag + SSAflag + L1L2flag + MOLHOflag + HOflag + FSflag):
    6060        raise TypeError("elements type not assigned, supported models are 'SIA', 'SSA', 'HO' and 'FS'")
    6161
    6262    #check that each element has only one flag
    63     if any(SIAflag + SSAflag + L1L2flag + MLHOflag + HOflag + FSflag > 1):
     63    if any(SIAflag + SSAflag + L1L2flag + MOLHOflag + HOflag + FSflag > 1):
    6464        print('Warning: setflowequation.py: some elements have several types, higher order type is used for them')
    6565        SIAflag[np.where(np.logical_and(SIAflag, SSAflag))] = False
     
    6767        SSAflag[np.where(np.logical_and(SSAflag, HOflag))] = False
    6868
    69         #check that L1L2 and MLHO is not coupled to any other model for now
     69        #check that L1L2 and MOLHO is not coupled to any other model for now
    7070        if any(L1L2flag) and any(SIAflag + SSAflag + HOflag + FSflag):
    7171            raise TypeError('L1L2 cannot be coupled to any other model')
    72         if any(MLHOflag) and any(SIAflag + SSAflag + HOflag + FSflag):
    73             raise TypeError('MLHO cannot be coupled to any other model')
     72        if any(MOLHOflag) and any(SIAflag + SSAflag + HOflag + FSflag):
     73            raise TypeError('MOLHO cannot be coupled to any other model')
    7474
    7575        #Check that no HO or FS for 2d mesh
     
    8989    nodeonL1L2 = np.zeros(md.mesh.numberofvertices, bool)
    9090    nodeonL1L2[md.mesh.elements[np.where(L1L2flag), :] - 1] = True
    91     nodeonMLHO = np.zeros(md.mesh.numberofvertices, bool)
    92     nodeonMLHO[md.mesh.elements[np.where(MLHOflag), :] - 1] = True
     91    nodeonMOLHO = np.zeros(md.mesh.numberofvertices, bool)
     92    nodeonMOLHO[md.mesh.elements[np.where(MOLHOflag), :] - 1] = True
    9393    nodeonHO = np.zeros(md.mesh.numberofvertices, bool)
    9494    nodeonHO[md.mesh.elements[np.where(HOflag), :] - 1] = True
     
    241241    md.flowequation.element_equation[np.where(SSAflag)] = 2
    242242    md.flowequation.element_equation[np.where(L1L2flag)] = 3
    243     md.flowequation.element_equation[np.where(MLHOflag)] = 4
     243    md.flowequation.element_equation[np.where(MOLHOflag)] = 4
    244244    md.flowequation.element_equation[np.where(HOflag)] = 5
    245245    md.flowequation.element_equation[np.where(FSflag)] = 6
     
    259259    pos = np.where(nodeonL1L2)
    260260    md.flowequation.vertex_equation[pos] = 3
    261     pos = np.where(nodeonMLHO)
     261    pos = np.where(nodeonMOLHO)
    262262    md.flowequation.vertex_equation[pos] = 4
    263263    pos = np.where(nodeonHO)
     
    283283    md.flowequation.isSSA = any(md.flowequation.element_equation == 2)
    284284    md.flowequation.isL1L2= any(md.flowequation.element_equation == 3)
    285     md.flowequation.isMLHO= any(md.flowequation.element_equation == 4)
     285    md.flowequation.isMOLHO= any(md.flowequation.element_equation == 4)
    286286    md.flowequation.isHO = any(md.flowequation.element_equation == 5)
    287287    md.flowequation.isFS = any(md.flowequation.element_equation == 6)
  • issm/trunk/src/m/plot/applyoptions.py

    r25836 r27035  
    5353    #title font
    5454        titlefont = font.copy()
    55         titlefont['size'] = titlefontsize
    56         titlefont['weight'] = titlefontweight
     55        titlefont['fontsize'] = titlefontsize
     56        titlefont['fontweight'] = titlefontweight
    5757        ax.set_title(title, **titlefont)
    5858    # }}}
  • issm/trunk/src/m/plot/plot_elementstype.m

    r25836 r27035  
    3737        end
    3838end
    39 legend(p,'None','SIA','SSA','L1L2','MLHO','HO',...
     39legend(p,'None','SIA','SSA','L1L2','MOLHO','HO',...
    4040                'SSAHO','FS','SSAFS','HOFS');
    4141
  • issm/trunk/src/m/plot/plot_manager.m

    r25836 r27035  
    129129                case 'transient_results',
    130130                        plot_transient_results(md,options,subplotwidth,i);
     131                        return
    131132                case 'transient_field',
    132133                        plot_transient_field(md,options,subplotwidth,i);
    133134                        return;
    134135        otherwise,
    135                 if ismember(data,properties('model')),
     136                if isfield(md.results,'TransientSolution') && isfield(md.results.TransientSolution,data)
     137                        plot_transient_movie(md,options,subplotwidth,i);
     138                        return
     139                elseif ismember(data,properties('model')),
    136140                        data=eval(['md.' data ';']);
    137141                else
  • issm/trunk/src/m/plot/plot_transient_movie.m

    r25836 r27035  
    1212        if exist(options,'transient_movie_field'),
    1313                field=getfieldvalue(options,'transient_movie_field');
     14        elseif ischar(getfieldvalue(options,'data'))
     15                field=getfieldvalue(options,'data');
    1416        else
    1517                disp('List of available fields:');
     
    3739                steps=[limit(1):limit(end)];
    3840        elseif exist(options,'transient_movie_steps'),
     41                warning('option ''transient_movie_steps'' is now ''steps'', please update your script');
    3942                steps = getfieldvalue(options,'transient_movie_steps');
     43        elseif exist(options,'steps'),
     44                steps = getfieldvalue(options,'steps');
    4045        else
    4146                steps=1:length(results);
     47        end
     48
     49        %Do we have an output?
     50        isavi = 0;
     51        isgif = 0;
     52        ismp4 = 0;
     53        if exist(options,'transient_movie_output'),
     54                filename=getfieldvalue(options,'transient_movie_output');
     55                [pathstr,name,ext] = fileparts(filename);
     56                if strcmp(ext,'.gif')
     57                        isgif = 1;
     58                elseif strcmp(ext,'.mp4')
     59                        ismp4 = 1;
     60                elseif strcmp(ext,'.avi')
     61                        isavi = 1;
     62                end
     63        end
     64        if isavi || ismp4
     65                vid=VideoWriter([filename(1:end-4),'.avi'],'Motion JPEG AVI');
     66                vid.FrameRate = 2;
     67                open(vid);
    4268        end
    4369
     
    5379        end
    5480
     81
     82        %Process mesh once for all
     83        [x y z elements is2d isplanet]=processmesh(md,results(i).(field),options);
     84
    5585        %display movie
    5686        nstep=1;
     
    6090                if ~isempty(results(i).(field)),
    6191                        %process data
    62                         [x y z elements is2d isplanet]=processmesh(md,results(i).(field),options);
    6392                        [data datatype]=processdata(md,results(i).(field),options);
    6493
    6594                        clf;
    66                         titlestring=[field ' at time ' num2str(results(i).time,'%7.2f') ' year'];
     95                        titlestring=[field ' (time ' num2str(results(i).time,'%7.2f') ' yr)'];
    6796                        plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
    68                         apply_options_movie(md,options,titlestring);
     97                        apply_options_movie(md,data,options,titlestring);
    6998
    70                         if exist(options,'transient_movie_output'),
    71                                 set(gcf,'Renderer','zbuffer','color','white'); %fixes a bug on Mac OS X (not needed in future Matlab version)
     99                        %Add grounding line
     100                        if exist(options,'groundingline')
     101                                if dimension(md.mesh)==2
     102                                        contours=isoline(md, results(i).MaskOceanLevelset,'output','matrix');
     103                                else
     104                                        ocean = project2d(md, results(i).MaskOceanLevelset, 1);
     105                                        contours=isoline(md, ocean,'output','matrix');
     106                                end
     107                                hold on
     108                                plot(contours(:,1),contours(:,2),getfieldvalue(options,'groundingline'));
     109                        end
     110
     111                        %Add ice front
     112                        if exist(options,'icefront')
     113                                if dimension(md.mesh)==2
     114                                        contours=isoline(md, results(i).MaskIceLevelset,'output','matrix');
     115                                else
     116                                        ice = project2d(md, results(i).MaskIceLevelset, 1);
     117                                        contours=isoline(md, ice,'output','matrix');
     118                                end
     119                                hold on
     120                                plot(contours(:,1),contours(:,2),getfieldvalue(options,'icefront'));
     121                        end
     122
     123                        if isgif
     124                                frame=getframe(gcf);
     125                                im = frame2im(frame);
     126                                [imind,cmap] = rgb2ind(im,256);
     127                                if i==1
     128                                        imwrite(imind, cmap, filename, 'DelayTime',getfieldvalue(options,'transient_movie_time',.5), 'LoopCount',inf)
     129                                else
     130                                        imwrite(imind, cmap, filename, 'WriteMode','append');
     131                                end
     132                        elseif isavi || ismp4
     133                                F=getframe(gcf);
     134                                writeVideo(vid, F);
     135                        end
     136
     137                        if exist(options,'transient_movie_output')
     138                                %set(gcf,'Renderer','zbuffer','color','white'); %fixes a bug on Mac OS X (not needed in future Matlab version)
    72139                                if nstep==1,
    73140                                        %initialize images and frame
     
    87154
    88155        %output movie if requested.
    89         if exist(options,'transient_movie_output'),
    90                 filename=getfieldvalue(options,'transient_movie_output');
    91                 imwrite(images,map,filename,'DelayTime',getfieldvalue(options,'transient_movie_time',2),'LoopCount',inf)
     156        if isavi || ismp4
     157                close(vid);
     158        end
     159        if ismp4
     160                filename = filename(1:end-4);
     161                while(~exist([filename '.avi']))
     162                        disp(['Waiting for ' filename '.avi']);
     163                        pause(1)
     164                end
     165                command=sprintf('ffmpeg -y -i %s.avi -c:v libx264 -crf 19 -preset slow -c:a libfaac -b:a 192k -ac 2 -vf "pad=ceil(iw/2)*2:ceil(ih/2)*2" %s.mp4',filename,filename);
     166                system(command);
     167        end
     168        if isgif
     169                imwrite(images,map,filename,'DelayTime',getfieldvalue(options,'transient_movie_time',.5),'LoopCount',inf)
    92170        end
    93171
    94172end %function
    95173
    96 function apply_options_movie(md,options,titlestring)
     174function apply_options_movie(md,data,options,titlestring)
    97175        %apply options
    98176        options=changefieldvalue(options,'title',titlestring);
    99177        options=addfielddefault(options,'colorbar',1);
    100         applyoptions(md,[],options);
     178        applyoptions(md,data,options);
    101179end
  • issm/trunk/src/m/plot/plot_vertexnumbering.m

    r17806 r27035  
    2020
    2121        %numbering
    22         text(x,y,z,num2str(vertexnumbers),...
    23                 'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
     22        X   = x;
     23        Y   = y;
     24        NUM = vertexnumbers;
     25        if exist(options,'axis')
     26                AXIS = getfieldvalue(options,'axis');
     27                pos = find(X>AXIS(1) & X<AXIS(2) & Y>AXIS(3) & Y<AXIS(4));
     28                X = X(pos); Y=Y(pos); NUM=NUM(pos);
     29        end
     30        text(X,Y,num2str(NUM),'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
    2431
    2532        %Highlight
     
    4552
    4653        %numbering
    47         text(x,y,z,num2str(vertexnumbers),...
    48                 'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
     54        X   = x;
     55        Y   = y;
     56        Z   = z;
     57        NUM = vertexnumbers;
     58        if exist(options,'axis')
     59                AXIS = getfieldvalue(options,'axis');
     60                pos = find(X>AXIS(1) & X<AXIS(2) & Y>AXIS(3) & Y<AXIS(4));
     61                X = X(pos); Y=Y(pos); Z=Z(pos); NUM=NUM(pos);
     62        end
     63        text(X,Y,Z,num2str(NUM),'backgroundcolor',[0.8 0.9 0.8],'HorizontalAlignment','center','VerticalAlignment','middle');
    4964
    5065        %Highlight
  • issm/trunk/src/m/shp/shpread.py

    r25836 r27035  
     1import numpy as np
    12from collections import OrderedDict
    23from os import path
     
    1213    """SHPREAD - read a shapefile and build a list of shapes
    1314
    14     This routine reads a shapefile and builds a list of OrderedDict objects 
    15     containing the fields x and y corresponding to the coordinates, one for the 
    16     filename of the shp file, for the density, for the nodes, and a field 
    17     closed to indicate if the domain is closed. If this initial shapefile is 
    18     point only, the fields closed and points are ommitted. The first argument 
    19     is the shapefile to be read and the second argument (optional) indicates if 
     15    This routine reads a shapefile and builds a list of OrderedDict objects
     16    containing the fields x and y corresponding to the coordinates, one for the
     17    filename of the shp file, for the density, for the nodes, and a field
     18    closed to indicate if the domain is closed. If this initial shapefile is
     19    point only, the fields closed and points are ommitted. The first argument
     20    is the shapefile to be read and the second argument (optional) indicates if
    2021    the last point shall be read (1 to read it, 0 not to).
    2122
     
    2627
    2728    Example:
    28         From underling PyShp implementation, "The shapefile format is actually 
    29         a collection of three files. You specify the base filename of the 
    30         shapefile or the complete filename of any of the shapefile component 
     29        From underling PyShp implementation, "The shapefile format is actually
     30        a collection of three files. You specify the base filename of the
     31        shapefile or the complete filename of any of the shapefile component
    3132        files."
    3233
     
    3738        list = shpread('domainoutline')
    3839
    39         "OR any of the other 5+ formats which are potentially part of a 
    40         shapefile. The library does not care about file extensions". We do, 
    41         however, check that a file with the base filename or base filename with 
     40        "OR any of the other 5+ formats which are potentially part of a
     41        shapefile. The library does not care about file extensions". We do,
     42        however, check that a file with the base filename or base filename with
    4243        .shp extension exists.
    4344
     
    4647
    4748    NOTE:
    48     - OrderedDict objects are used instead of OrderedStruct objects (although 
    49     addressing in the latter case is closer to the MATLAB struct type) in order 
     49    - OrderedDict objects are used instead of OrderedStruct objects (although
     50    addressing in the latter case is closer to the MATLAB struct type) in order
    5051    to remain consistent with the pattern established by src/m/exp/expread.py.
    5152
    5253    TODO:
    53     - Create class that can be used to store and pretty print shape structs 
     54    - Create class that can be used to store and pretty print shape structs
    5455    (ala OrderedStruct from src/m/qmu/helpers.py).
    55     - Convert returned data structure from list of OrderedDict objects to list 
    56     of OrderedStruct objects and remove corresponding note (see also 
     56    - Convert returned data structure from list of OrderedDict objects to list
     57    of OrderedStruct objects and remove corresponding note (see also
    5758    src/m/exp/expread.py). Also, modify handling of returned data structure in,
    5859        - src/m/classes/basin.py
     
    7677    Structs = []
    7778    shapes = sf.shapes()
    78     for i in range(len(shapes)):
     79    for i, shape in enumerate(shapes):
    7980        Struct = OrderedDict()
    80         shape = shapes[i]
    8181        if shape.shapeType == shapefile.POINT:
    8282            Struct['x'] = shape.points[0][0]
     
    8888            x = []
    8989            y = []
    90             for j in range(num_points):
    91                 point = shape.points[j]
     90            for j, point in enumerate(shape.points):
    9291                x.append(point[0])
    9392                y.append(point[1])
     
    103102            x = []
    104103            y = []
    105             for j in range(num_points):
    106                 point = shape.points[j]
     104            for j, point in enumerate(shape.points):
    107105                x.append(point[0])
    108106                y.append(point[1])
     
    115113            Struct['Geometry'] = 'Polygon'
    116114        else:
    117             # NOTE: We could do this once before looping over shapes as all 
    118             #       shapes in the file must be of the same type, but we would 
    119             #       need to have a second check anyway in order to know how to 
    120             #       parse the points. So, let's just assume the file is not 
     115            # NOTE: We could do this once before looping over shapes as all
     116            #       shapes in the file must be of the same type, but we would
     117            #       need to have a second check anyway in order to know how to
     118            #       parse the points. So, let's just assume the file is not
    121119            #       malformed.
    122120            #
     
    125123        name = ''
    126124        fields = sf.fields
    127         for j in range(1, len(fields)): # skip over first field, which is "DeletionFlag"
     125        for j in range(1, len(fields)):  # skip over first field, which is "DeletionFlag"
    128126            fieldname = fields[j][0]
    129127            # 'id' field gets special treatment
    130             if fieldname == 'id':
    131                 name = str(sf.record(i)[j - 1]) # record index is offset by one, again, because of "DeletionFlag"
     128            if fieldname in ['id', 'fid']:
     129                name = str(sf.record(i)[j - 1])  # record index is offset by one, again, because of "DeletionFlag"
    132130            else:
    133                 setattr(Struct, str(fieldname), sf.record(i)[j - 1]) # cast to string removes "u" from "u'fieldname'"
     131                setattr(Struct, str(fieldname), sf.record(i)[j - 1])  # cast to string removes "u" from "u'fieldname'"
    134132        Struct['name'] = name
    135133        Structs.append(Struct)
  • issm/trunk/src/m/shp/shpwrite.py

    r25836 r27035  
    2323
    2424    TODO:
    25     - Should we check if there is only one element (see how MATLAB's shaperead 
     25    - Should we check if there is only one element (see how MATLAB's shaperead
    2626    and shapewrite handle single shapes versus multiple shapes)?
    2727    '''
     
    4343
    4444    for i in range(len(shp)):
    45         sf.field('name', 'C') # TODO: Allow shape ids/names to be passed through
     45        sf.field('name', 'C')  # TODO: Allow shape ids/names to be passed through
    4646        if shapeType == 1: # POINT
    4747            sf.point(shp[i].x, shp[i].y)
     
    5151                points.append([shp[i].x[j], shp[i].y[j]])
    5252            sf.line(line)
    53         elif shapeType == 5: # POLYGON
     53        elif shapeType == 5:  # POLYGON
    5454            points = []
    5555            for j in range(len(shp[i].x)):
  • issm/trunk/src/m/solve/parseresultsfromdisk.m

    r26744 r27035  
    244244                field = field*yts;
    245245        elseif strcmp(fieldname,'BasalforcingsFloatingiceMeltingRate'),
     246                field = field*yts;
     247        elseif strcmp(fieldname,'BasalforcingsSpatialDeepwaterMeltingRate'),
     248                field = field*yts;
     249        elseif strcmp(fieldname,'BasalforcingsSpatialUpperwaterMeltingRate'),
    246250                field = field*yts;
    247251        elseif strcmp(fieldname,'TotalFloatingBmb'),
  • issm/trunk/src/m/solve/parseresultsfromdisk.py

    r26744 r27035  
    195195            field = field * yts
    196196        elif fieldname == 'BasalforcingsFloatingiceMeltingRate':
     197            field = field * yts
     198        elif fieldname == 'BasalforcingsSpatialDeepwaterMeltingRate':
     199            field = field * yts
     200        elif fieldname == 'BasalforcingsSpatialUpperwaterMeltingRate':
    197201            field = field * yts
    198202        elif fieldname == 'TotalFloatingBmb':
  • issm/trunk/src/wrappers/CoordTransform/CoordTransform.cpp

    r26744 r27035  
    6565                }
    6666
    67                 PJ *P;
    6867                size_t sx = sizeof(double);
    6968                size_t sy = sizeof(double);
     
    7170                size_t ny = size;
    7271
    73                 P = proj_create_crs_to_crs(PJ_DEFAULT_CTX,projin,projout,NULL);
     72                PJ* P = proj_create_crs_to_crs(PJ_DEFAULT_CTX,projin,projout,NULL);
    7473
    75                 if ( 0 == P ) {
     74                if(P==0){
    7675                        proj_destroy(P);
    77                         _error_("failed to initialize CRS transformation object");
     76                        _error_("Projection string not recognized");
    7877                }
    7978
    8079                int p = proj_trans_generic(P, PJ_FWD, xout, sx, nx, yout, sy, ny, 0, 0, 0, 0, 0, 0);
    8180
    82                 if ( 0 == p ){
     81                if(p==0){
    8382                        proj_destroy(P);
    84                         _error_("no successful transformations");
     83                        _error_("projection failed");
    8584                }
    8685
     86                /*Cleanup*/
    8787                proj_destroy(P);
    8888
Note: See TracChangeset for help on using the changeset viewer.