1 2 #include <../src/vec/pf/pfimpl.h> /*I "petscpf.h" I*/ 3 #include <petscmatlab.h> /*I "petscmatlab.h" I*/ 4 5 /* 6 This PF generates a MATLAB function on the fly 7 */ 8 typedef struct { 9 PetscInt dimin,dimout; 10 PetscMatlabEngine mengine; 11 char *string; 12 } PF_Matlab; 13 14 PetscErrorCode PFView_Matlab(void *value,PetscViewer viewer) 15 { 16 PetscBool iascii; 17 PF_Matlab *matlab = (PF_Matlab*)value; 18 19 PetscFunctionBegin; 20 PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii)); 21 if (iascii) PetscCall(PetscViewerASCIIPrintf(viewer,"Matlab Matlab = %s\n",matlab->string)); 22 PetscFunctionReturn(0); 23 } 24 25 PetscErrorCode PFDestroy_Matlab(void *value) 26 { 27 PF_Matlab *matlab = (PF_Matlab*)value; 28 29 PetscFunctionBegin; 30 PetscCall(PetscFree(matlab->string)); 31 PetscCall(PetscMatlabEngineDestroy(&matlab->mengine)); 32 PetscCall(PetscFree(matlab)); 33 PetscFunctionReturn(0); 34 } 35 36 PetscErrorCode PFApply_Matlab(void *value,PetscInt n,const PetscScalar *in,PetscScalar *out) 37 { 38 PF_Matlab *matlab = (PF_Matlab*)value; 39 40 PetscFunctionBegin; 41 PetscCheck(value,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Need to set string for MATLAB function, via -pf_matlab string"); 42 PetscCall(PetscMatlabEnginePutArray(matlab->mengine,matlab->dimin,n,in,"x")); 43 PetscCall(PetscMatlabEngineEvaluate(matlab->mengine,matlab->string)); 44 PetscCall(PetscMatlabEngineGetArray(matlab->mengine,matlab->dimout,n,out,"f")); 45 PetscFunctionReturn(0); 46 } 47 48 PetscErrorCode PFSetFromOptions_Matlab(PetscOptionItems *PetscOptionsObject,PF pf) 49 { 50 PetscBool flag; 51 char value[256]; 52 PF_Matlab *matlab = (PF_Matlab*)pf->data; 53 54 PetscFunctionBegin; 55 PetscOptionsHeadBegin(PetscOptionsObject,"Matlab function options"); 56 PetscCall(PetscOptionsString("-pf_matlab","Matlab function","None","",value,sizeof(value),&flag)); 57 if (flag) PetscCall(PetscStrallocpy((char*)value,&matlab->string)); 58 PetscOptionsHeadEnd(); 59 PetscFunctionReturn(0); 60 } 61 62 PETSC_EXTERN PetscErrorCode PFCreate_Matlab(PF pf,void *value) 63 { 64 PF_Matlab *matlab; 65 66 PetscFunctionBegin; 67 PetscCall(PetscNewLog(pf,&matlab)); 68 matlab->dimin = pf->dimin; 69 matlab->dimout = pf->dimout; 70 71 PetscCall(PetscMatlabEngineCreate(PetscObjectComm((PetscObject)pf),NULL,&matlab->mengine)); 72 73 if (value) PetscCall(PetscStrallocpy((char*)value,&matlab->string)); 74 PetscCall(PFSet(pf,PFApply_Matlab,NULL,PFView_Matlab,PFDestroy_Matlab,matlab)); 75 76 pf->ops->setfromoptions = PFSetFromOptions_Matlab; 77 PetscFunctionReturn(0); 78 } 79