Monday, December 22, 2025

Programming an estimation command in Stata: Writing a Java plugin


This submit is the fourth in a sequence that illustrates the right way to plug code written in one other language (like C, C++, or Java) into Stata. This system is called writing a plugin or as writing a dynamic-link library (DLL) for Stata.

On this submit, I write a plugin in Java that implements the calculations carried out by mymean_work() in mymean11.ado, mentioned in Programming an estimation command in Stata: Making ready to jot down a plugin, and I assume that you’re conversant in that materials.

This submit is analogous to Programming an estimation command in Stata: Writing a C plugin and to Programming an estimation command in Stata: Writing a C++ plugin. The variations are because of the plugin code being in Java as a substitute of C or C++. I don’t assume that you’re conversant in the fabric in these posts, and far of that materials is repeated right here.

That is the thirty second submit within the sequence Programming an estimation command in Stata. See Programming an estimation command in Stata: A map to posted entries for a map to all of the posts on this sequence.

Writing a hello-world Java plugin

Earlier than I do any computations, I illustrate the right way to write and to compile a Java plugin that communicates with Stata. Code block 1 accommodates the code for myhellojava.ado that calls a Java plugin that makes Stata show “Good day from Java”.

Code block 1: myhellojava.ado


*! model 1.0.0 14Feb2018
program myhellojava

       model 15.1

       javacall HelloFromJava helloJavaWork, jar(hellojavawork.jar)
finish

In line 6, javacall executes the helloJavaWork technique of the category HelloFromJava, which is within the JAR file hellojavawork.jar.

HelloFromJava.java in code block 2 accommodates the code for the HelloFromJava class.

Code block 2: HelloFromJava.java


// model 1.0.0 14Feb2018
import com.stata.sfi.*;
public class HelloFromJava {
        public static int helloJavaWork(String[] args) {
                SFIToolkit.displayln("Good day from Java") ;
                return(0) ;      // Stata return code
       }
}

Line 2 imports the Stata perform interface (SFI) from sfi-api.jar, which I copied to the present listing from the Stata/utilities/jar listing distributed with Stata. It is best to copy the model put in together with your Stata to the listing your Java compiler requires.

Line 3 defines the general public class HelloFromJava, specified on line 6 of myhellojava.ado.

Line 4 defines the helloJavaWork() technique, which is the entry level for the plugin. The signature of the entry technique have to be of this way. The tactic is public static. The tactic returns an int. The tactic accepts a String array.

Stata treats the returned int as a return code; zero means all went properly and never zero identifies an error situation. Stata will exit with the error specified within the returned int if the returned int will not be zero. The String array accommodates the arguments handed to the plugin by javacall.

Line 5 makes use of the SFI technique SFIToolkit.displayln() to show the String “Good day from Java” with an extra line return.

Line 6 returns 0 to Stata, so Stata won’t exit with an error code.

I now talk about the right way to create the JAR file hellojavawork.jar from HelloFromJava.java. I take advantage of the Java command-line instruments to facilitate this dialogue. See Working with Java plugins (Half 1) for particulars about utilizing the Eclipse built-in improvement surroundings (IDE).

Within the listing that accommodates myhellojava.ado and HelloFromJava.java, I even have the sfi-api.jar that I copied from the Stata/utilities/jar listing. On my OS X Mac that has the command-line developer instruments put in, I take advantage of javac to create HelloFromJava.class from HelloFromJava.java and sfi-api.jar by typing

javac –launch 8 -classpath sfi-api.jar HelloFromJava.java

On the time of this writing, Stata works with Java 8, though Java 9 is having its preliminary launch. I needed to specify –launch 8, as a result of the command-line instruments on my machine work with Java 9 by default. You’ll be able to omit this selection if javac defaults to Java 8 in your machine.

To create the JAR file hellojavawork.jar from HelloFromJava.class, I typed

jar cf hellojavawork.jar HelloFromJava.class

These instructions for javac and jar work on all platforms, and you may distribute the jar file made on one platform to different platforms. This cross-platform compatibility is a serious benefit of Java.

To make sure that the Stata command discard drops all of the Java lessons at present loaded into Stata, I additionally delete the .class compiled by javac earlier than I run the ado-command that makes use of a Java class. On my OS X Mac, I kind

rm HelloFromJava.class

Having created hellojavawork.jar and deleted HelloFromJava.class, I can execute myhellojava.ado in Stata.

Instance 1: myhellocjava


. myhellojava
Good day from Java

If I modify HelloFromJava.java, recompile, remake the JAR file, delete the .class file, and sort discard in Stata earlier than working myhellojava, Stata will discover the brand new model of the Java class. discard works as a result of Stata’s Java plugin interface makes use of a customized class loader as a substitute of the Java-system class loader to load a plugin’s JAR file. An issue happens while you depart your .class recordsdata in Stata’s present working listing, as a result of the Java-system class loader will discover and cargo the .class recordsdata earlier than Stata’s customized class loader can act. This downside prevents Stata’s discard command from unloading the lessons, which signifies that it’s essential to restart Stata to unload outdated class definitions and to load new variations. To forestall this downside, delete the .class recordsdata earlier than calling your Java plugin. (Alternatively, you might work together with your Java code outdoors of Stata’s present working listing, however I choose deleting the .class recordsdata, as a result of they’re superfluous as soon as I’ve the JAR recordsdata.)

For simplicity, I’ve sfi-api.jar, HelloFromjava.java, myhellojava.ado, and hellojavawork.jar in the identical listing. For big tasks, I might put the .ado and .jar recordsdata in directories on Stata’s ADOPATH and use my IDE to handle the place I put sfi-api.jar and the Java supply recordsdata. For the examples on this submit, I put sfi-api.jar, all my .ado recordsdata, all my Java supply recordsdata, and the created .jar recordsdata right into a single listing.

Having access to the Stata information in your plugin

helloJavaWork() makes Stata show one thing created contained in the plugin. The following step is giving the plugin entry to the info in Stata. For instance this course of, I talk about mylistjava.ado, which makes use of a plugin to listing out observations of the desired variables.

Let’s take a look at the ado-code first.

Code block 3: mylistjava.ado


*! model 1.0.0  14Feb2018
program outline mylistjava

    model 15.1

    syntax varlist(numeric max=3) [if] [in]
    marksample touse

    show "Variables listed:  `varlist'"
    javacall MyListJava myListJW `varlist' if `touse' `in',  jar(mylistjw.jar)

finish

In line 6, syntax creates three native macros. It places the variables specified by the person into the native macro varlist. It places any if situation specified by the person into the native macro if. It places any in vary specified by the person into the native macro in. I specified max=3 to syntax to restrict the variety of variables to three. This limitation is foolish, and I might not want it for an instance Stata/Mata program, however it simplifies the instance Java plugin.

In line 7, marksample creates a sample-inclusion variable, and it places the title of the sample-inclusion variable within the native macro touse. The sample-inclusion variable is zero for every excluded commentary, and it’s one for every included commentary. marksample makes use of the variables within the native macro varlist, the if situation within the native macro if, and the vary within the native macro in to create the sample-inclusion variable. (All three native macros have been created by syntax.) An commentary is excluded if any of the variables within the native macro varlist include a lacking worth, if it was excluded by the situation within the native macro if, or if it was excluded by the vary within the native macro in. The sample-inclusion variable is one for observations that weren’t excluded.

In line 9, I additional simplified the Java plugin by displaying the names of the variables whose values are listed out by the tactic plugin.

In line 10, javacall calls the plugin. The entry level is the tactic myListJW() within the class MyListJava, which is outlined within the JAR file mylistjw.jar. As a result of `varlist’ is specified, SFI strategies will be capable to entry the variables contained within the native macro varlist. As a result of if `touse’ is specified, the SFI technique Information.isParsedIfTrue() will return zero if the sample-inclusion variable in `touse’ is zero, and it’ll return one if the sample-inclusion variable is one. As a result of `in’ is specified, the SFI strategies Information.getObsParsedIn1() and Information.getObsParsedIn2() respectively return the primary and the final observations in any user-specified in vary.

Specifying `in’ will not be essential to establish the pattern specified by the person, as a result of if `touse’ already specifies this sample-inclusion data. Nevertheless, specifying `in’ can dramatically cut back the vary of observations within the loop over the info, thereby dashing up the code.

The code for MyListJava is in code block 4. In a listing that accommodates MyListJava.java and sfi-api.jar, I created mylistjw.jar on my Mac by typing the next three strains.

javac –launch 8 -classpath sfi-api.jar MyListJava.java

jar cf mylistjw.jar MyListJava.class

rm MyListJava.class

Code block 4: MyListJava.java


// model 1.0.0 14Feb2018
import com.stata.sfi.*;
public class MyListJava {
    public static int myListJW(String[] args) {

// line will probably be displayed by Stata
        String line  ;

// Get variety of variables in varlist specified to javacall
        int  nVariables = Information.getParsedVarCount();
// Get first commentary specified by an in restriction
        lengthy firstObs   = Information.getObsParsedIn1();
// Get final commentary specified by an in restriction
        lengthy lastObs    = Information.getObsParsedIn2();

// counter for numerber of obs in pattern
        lengthy nObs            = 0 ;
// Loop over observations
        for (lengthy obs = firstObs; obs <= lastObs; obs++) {
            if (!Information.isParsedIfTrue(obs)) {
                        proceed;
            }
// Increment counter
            ++nObs ;
            line = "" ;
// Loop over variables
            for (int j = 1; j <= nVariables; j++) {
                int varIndex = Information.mapParsedVarIndex(j);
                double worth = Information.getNum(varIndex, obs);
                if (Information.isValueMissing(worth)) {
                    line = "lacking values encountered" ;
                    SFIToolkit.errorln(line);
                    return(416) ;
                }
                line += String.format("   %9s",
                    SFIToolkit.formatValue(worth,  "%9.0g") );
            }
            SFIToolkit.displayln(line);
        }
        SFIToolkit.displayln("First commentary was             " + firstObs) ;
        SFIToolkit.displayln("Final commentary was              " + lastObs) ;
        SFIToolkit.displayln("Variety of observations listed was " + nObs) ;

        return(0) ;
    }
}

If you’re studying this submit, you possibly can learn normal Java. I clarify how MyListJava.java illustrates the construction of Java plugins for Stata, and I talk about the SFI strategies used within the code. Full particulars concerning the SFI can be found at https://www.stata.com/java/api15/, which builds on the [P] java handbook entry and the [P] java name handbook entry.

myListJW.java returns zero to Stata if all went properly, and it returns a nonzero error code if one thing went mistaken. As a result of not one of the strategies known as can fail, the one error situation addressed is encountering lacking values, which is dealt with in strains 30–34. Within the case of an error, line 32 makes use of SFIToolkit.errorln() to make sure that the error message is displayed by Stata and that it’s displayed in crimson. SFIToolkit.show() is the usual show technique used elsewhere within the code.

Java plugins learn from or write to Stata objects utilizing strategies outlined within the SFI. myListJW() doesn’t return any outcomes, so it has a easy construction.

  • It makes use of SFI strategies to learn from the desired pattern of the info in Stata.
  • It makes use of normal Java and SFI strategies to make Stata show observations on variables for the desired pattern, and it retains a counter of what number of observations are within the specified pattern.
  • It makes use of normal Java and SFI strategies to show which was the primary commentary within the pattern, which was the final commentary within the pattern, and what number of observations have been within the specified pattern.

Now, I talk about particular components of MyListJava.java.

Traces 10, 12, and 14 use strategies of SFI Information class. Information.getParsedVarCount() places the variety of variables specified within the varlist into nVariables. Information.getObsParsedIn1() places the primary commentary specified by an in vary into firstObs. Information.getObsParsedIn2() places the final commentary specified by an in vary into lastObs. If an in vary was not specified to javacall, firstObs will include 1, and lastObs will include the variety of observations within the dataset.

firstObs, lastObs, and all Java variables that maintain Stata commentary numbers are of kind lengthy, as a result of Stata datasets can include extra observations than would match right into a Java variable of kind int.

Traces 20–22 make sure that we skip over observations that have been excluded by the if restriction specified to javacall in line 10 of mylistjava.ado. For instance some particulars, contemplate instance 2.

Instance 2: mylistjava


. sysuse auto, clear
(1978 Car Information)

. mylistjava mpg trunk rep78 if trunk < 21 in 2/10
Variables listed:  mpg trunk rep78
          17          11           3
          20          16           3
          15          20           4
          20          16           3
          16          17           3
          19          13           3
First commentary was             2
Final commentary was              10
Variety of observations listed was 6

In line 20, Information.isParsedIfTrue(obs) returns one when the if restriction specified to javacall is one for commentary obs, and it’s zero in any other case. In line 10 of mylistjava.ado, we see that the if restriction handed to javacall is if `touse’. As mentioned above, the sample-inclusion variable within the native macro touse is zero for excluded observations, and it’s one for the included observations.

The in vary on line 10 of mylistjava.ado was included in order that the loop over the observations in line 19 of MyListJava.java would solely go from the start to the top of any specified in vary. In instance 2, as a substitute of looping over all 74 observations within the auto dataset, the loop on line 19 of MyListJava.java solely goes from 2 to 10.

In instance 2, the sample-inclusion variable is 1 for six observations, and it’s 0 for the opposite 68 observations. The in 2/10 vary excludes commentary 1 and the observations from 11–74. Of the primary 10 observations, 2 are excluded as a result of rep78 is lacking. One commentary is excluded as a result of trunk is 21.

For comparability, all 9 observations between 2 and 10 are listed in instance 3.

Instance 3: listing


. listing mpg trunk rep78 in 2/10, separator(0)

     +---------------------+
     | mpg   trunk   rep78 |
     |---------------------|
  2. |  17      11       3 |
  3. |  22      12       . |
  4. |  20      16       3 |
  5. |  15      20       4 |
  6. |  18      21       3 |
  7. |  26      10       . |
  8. |  20      16       3 |
  9. |  16      17       3 |
 10. |  19      13       3 |
     +---------------------+

Returning to MyListJava, we see that strains 28–29 illustrate the right way to put the worth of a Stata numeric variable right into a Java variable. Be aware that Information.getNum() returns a double for all Stata numeric variable sorts. In instance 2, mpg, trunk, and rep78 are all of kind int in Stata.

Traces 30–34 trigger myListJW() to exit with error 416 if any commentary in one of many variables accommodates a lacking worth. These strains are redundant, as a result of the sample-inclusion variable in touse specified to javacall excluded observations containing lacking values. I included these strains for instance how I might safely exclude lacking values from contained in the plugin and to reiterate that Java code should rigorously take care of lacking values. Stata lacking values are legitimate double precision numbers in Java. You’ll get mistaken outcomes if you happen to embrace Stata lacking values in calculations.

Estimating the imply in a Java plugin

I now talk about the ado-command mymeanjava, which makes use of the myWork() technique within the MyCalcs class to implement the calculations carried out by mymean_work() in mymean11.ado, mentioned in Programming an estimation command in Stata: Making ready to jot down a plugin.

The code for mymeanjava is in mymeanjava.ado, which is in code block 5.

Code block 5: mymeanjava.ado


*! model 1.0.0  14Feb2018
program outline mymeanjava, eclass

    model 15.1

    syntax varlist(numeric) [if] [in]
    marksample touse
    tempname b V N

    javacall MyCalcs myWork `varlist' if `touse' `in',  ///
        jar(mycalcs.jar) args(`b' `V' `N')

    matrix colnames `b'  = `varlist'
    matrix colnames `V'  = `varlist'
    matrix rownames `V'  = `varlist'
    ereturn submit `b' `V', esample(`touse')
    ereturn scalar   N   = `N'
    ereturn scalar df_r  = `N'-1
    ereturn show

finish

The overall construction of this program is just like mymean10.ado and mymean11, mentioned in Programming an estimation command in Stata: Making ready to jot down a plugin.

From a chook’s-eye view, mymeanjava.ado

  • parses the person enter;
  • creates a sample-inclusion variable;
  • creates short-term names for objects that can maintain the outcomes;
  • calls a piece program to do the calculations;
  • shops the outcomes returned by the work program in e(); and
  • shows the outcomes.

The principle distinction between mymeanjava.ado and mymean11.ado is that the work program is a Java plugin as a substitute of a Mata perform.

Traces 6 and seven are similar to these in mylistjava.ado. For an outline of how these strains create the native macro varlist, the sample-inclusion variable contained within the native macro touse, and the native macro in that accommodates any user-specified in vary, see the dialogue of mylistjava.ado in Having access to the Stata information in your plugin.

Line 8 places short-term names into the native macros b, V, and N. We are able to use these names for outcomes computed by the Java plugin and know that we’ll not overwrite any outcomes {that a} person has saved in international Stata reminiscence. (Recall that Stata matrices and scalars are international objects in Stata; see Utilizing short-term names for international objects in Programming an estimation command in Stata: A primary ado-command for a dialogue of this matter.) As well as, Stata will drop the objects within the short-term names created by tempname when mymeanjava terminates.

Line 10 in mymeanjava is just like its counterpart of line 10 in mylistjava.ado. On this case, myWork() is the entry technique outlined within the class MyCalcs, which is within the JAR file mycalcs.jar. The main points of varlist, if `touse’, and `in’ have been mentioned above. What’s new is that we use args(`b’ `V’ `N’) to move the short-term names to myWork().

The myWork(),

  • does the calculations;
  • places the estimated means into a brand new Stata matrix whose title is within the native macro b;
  • places the estimated variance–covariance of the estimator (VCE) into a brand new Stata matrix whose title is within the native macro V; and
  • places the variety of observations within the pattern into the Stata scalar whose title is within the native macro N.

Traces 13–15 put the variable names on the column stripe of the vector of estimated means and on the row and column stripes of the VCE matrix. Traces 16–18 retailer the leads to e(). Line 19 shows the outcomes.

Earlier than discussing the small print of myWork(), let’s create the plugin and run an instance.

In a listing that accommodates MyCalcs.java, MyCalcsW.java, MyMatrix.java, MyLong.java, and sfi-api.jar, I created mycalcs.jar on my Mac by typing

javac –release 8 -classpath MyCalcs.java MyCalcsW.java MyMatrix.java MyLong.java sfi-api.jar

jar cf mycalcs.jar MyCalcs.class MyCalcsW.class MyMatrix.class MyLong.class

rm MyCalcs.class MyCalcsW.class MyMatrix.class MyLong.class

Having created mycalcs.jar, I ran instance 3.

Instance 4: mymeanjava


. mymeanjava mpg trunk rep78 in 1/60
------------------------------------------------------------------------------
             |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
         mpg |     20.125   .6659933    30.22   0.000     18.79032    21.45968
       trunk |   14.42857   .5969931    24.17   0.000     13.23217    15.62497
       rep78 |   3.160714    .118915    26.58   0.000     2.922403    3.399025
------------------------------------------------------------------------------

I now talk about some facets of the Java code, starting with the category MyCalcs.java in code block 6.

Code block 6: MyCalcs.java


// model 1.0.0 14Feb2018
import com.stata.sfi.*;
public class MyCalcs {
    public static int myWork(String args[]) {
        int      rc ;
        MyMatrix bmat, vmat ;
        String   bname, vname, nname ;
        MyLong   nObs ;

        if (args.size < 3) {
            SFIToolkit.errorln("Too few arguments") ;
            return 198 ;
        }
        else {
            bname = args[0] ;
            vname = args[1] ;
            nname = args[2] ;
        }

        int  nVariables = Information.getParsedVarCount();
        lengthy firstObs   = Information.getObsParsedIn1();
        lengthy lastObs    = Information.getObsParsedIn2();

// create and initialize vector for pattern averages
        bmat = new MyMatrix(1, nVariables);
// create and initialize matrix for VCE
        vmat = new MyMatrix(nVariables, nVariables);
// create and initialize MyLong for pattern measurement
        nObs    = new MyLong(0) ;

// Put pattern averages in bmat
        rc = MyCalcsW.myAve(bmat, firstObs, lastObs, nVariables, nObs) ;
        if (rc>0) return(rc) ;
// Put VCE in vmat
        rc = MyCalcsW.myV(bmat, vmat, firstObs, lastObs, nVariables, nObs) ;
        if (rc>0) return(rc) ;

// Copy pattern common from bmat to Stata matrix bname
        rc = bmat.copyJavatoStataMatrix(bname) ;
        if (rc>0) return(rc) ;
// Copy VCE from vmat to Stata matrix vname
        rc = vmat.copyJavatoStataMatrix(vname) ;
        if (rc>0) return(rc) ;
// Copy pattern measurement from n to Stata scalar nname
        rc = Scalar.setValue(nname, (double) nObs.getValue()) ;
        if (rc>0) return(rc) ;

        return(rc);
    }
}

MyCalcs.java solely accommodates the entry technique myWork(). In abstract, myWork() performs the next duties.

  1. It places the names handed in as arguments into cases of Java String objects that may be handed to SFI strategies.
  2. It places the variety of specified Stata variables right into a Java variable used to loop over the variables.
  3. It places the vary of pattern observations into Java variables used to
    loop over the observations.
  4. It creates the bmat and vmat cases of the MyMatrix class, which can maintain the pattern averages and the VCE.
  5. It creates the nObs occasion of the MyLong class, which can maintain the variety of pattern observations.
  6. It makes use of the strategies MyCalcsW.myAve() and MyCalcsW.myV() to
    compute the outcomes which are saved in bmat, vmat, and nObs.
  7. It makes use of the tactic CopyCtoStataMatrix() of the MyMatrix class to repeat the outcomes from bmat and vmat to new Stata matrices. The names of the brand new Stata matrices are the primary and second arguments handed to myWork().
  8. It makes use of the SFI technique Scalar.setValue() to repeat the outcome from nObs to the brand new Stata scalar whose title was the third argument handed to myWork().

MyCalcs.java is simple to learn, as a result of I put all the small print into the MyMatrix, MyCalcsW, and MyLong lessons, which I talk about beneath.

Like all Java plugins for Stata, myWork() makes use of the return code rc to deal with error situations. Every technique known as returns zero if all went properly, and it returns a nonzero error code if it couldn’t carry out the requested job. If the code returned will not be zero, myWork() returns it instantly to Stata. The error messages related to the error situations are displayed by the strategies.

In (3), I famous that bmat and vmat are cases of the MyMatrix class. The pattern averages and the VCE are greatest saved in matrices. To maintain issues easy and self-contained, I outlined a bare-bones matrix class MyMatrix that makes use of row-major storage and solely the strategies I wanted. Apart from the tactic copyJavatoStataMatrix(), the code for MyMatrix is normal Java, as might be seen in code block 7.

Code block 7: MyMatrix.java


// model 1.0.0 14Feb2018
// Notes: matrices are lengthy vectors with row-major storage
//    The i,j factor of an r x c matrix is 
//    the (i-1)*r + (j-1) factor of the of the vector
//    below zero-base indexing
import com.stata.sfi.*;
public class MyMatrix {
    int        r, c, TotalSize ;
    double[]   mat ;

    public MyMatrix(int rows, int cols) {
        r         = rows ;
        c         = cols ;
        TotalSize = rows*cols ;
        mat       = new double[TotalSize] ;

        for(int i = 0; i0) {
            SFIToolkit.errorln("can't create Stata matrix " + smname) ;
            return(rc_st) ;
        }
        for(i=0; i0) {
                    msg =  "{err}can't entry Stata matrix " + smname ;
                    SFIToolkit.errorln(msg) ;
                    return(rc_st) ;
                }
            }
        }
        return(rc_st) ;
    }

    double getValue(int i, int j) {
        return( mat[i*r+j]) ;
    }
// Retailer val into (i,j)th factor 
    void storeValue(int i, int j, double val) {
        mat[i*r+j] = val ;
    }
// Increment (i,j)th factor  by val
    void incrementByValue(int i, int j, double val) {
        mat[i*r+j] += val ;
    }

}

Traces 33–58 include the code for copyJavatoStataMatrix(). Traces 40 and 49 use SFI strategies that I’ve not but mentioned. Matrix.createMatrix(String sname, int rows, int cols, double val) creates a brand new Stata matrix with rows rows and cols columns. Every factor of this matrix is initialized to worth val. sname accommodates the title of this Stata matrix.

Matrix.storeMatrixAt(String sname, int i, int j, double val) shops the worth val in row i and column j of the Stata matrix whose title is contained in sname. The row i and column j are given in zero-based indexing.

In (4), I famous that I used an occasion of the MyLong class to carry the variety of pattern observations. The primitive sorts in Java can’t be handed by reference, and the usual wrapper sorts are immutable, so I created to move a lengthy counter, nObs, to MyCalcsW.myAve(). When MyCalcsW.myAve() finishes, nObs accommodates the variety of pattern observations. The code for MyLong is normal Java, and it’s given in code block 8.

Code block 8: MyLong.java


// model 1.0.0 14Feb2018
public class MyLong {
    personal lengthy worth ;

    public MyLong(lengthy j) {
        worth = j ;
    }

    public lengthy getValue() {
        return worth ;
    }

    public void setValue(lengthy j) {
        worth = j;
    }

    public void incrementValue() {
        ++(worth) ;
    }
}

In (5), I notice that the strategies MyCalcsW.myAve() and MyCalcsW.myV compute the pattern averages and the VCE. These are strategies within the class MyCalcsW, whose code is given in code block 9.

Code block 9: MyCalcsW.java


// model 1.0.0 14Feb2018
import com.stata.sfi.*;
public class MyCalcsW {

    public static int myAve( MyMatrix bmat, lengthy firstObs, lengthy lastObs,
        int nVariables, MyLong nObs) {

        int    rc, varIndex ;
        double worth ;
        String msg ;

        rc = 0 ;
// Loop over observations
        for(lengthy obs=firstObs; obs<=lastObs; obs++) {
            if (!Information.isParsedIfTrue(obs)) {
                proceed;
            }
            nObs.incrementValue() ;

// Loop over variables
            for(int var = 1; var<=nVariables; var++) {
// get the actual variable index for parsed variable -var-
                varIndex = Information.mapParsedVarIndex(var);
// Put worth of commentary obs on variable varIndex into worth
                worth    = Information.getNum(varIndex, obs);

// Exit with error 
                if (Information.isValueMissing(worth)) {
                    msg = "{err}lacking values encountered" ;
                    SFIToolkit.errorln(msg);
                    return(416) ;
                }
// Increment pattern common vector
                bmat.incrementByValue(0, var-1, worth) ;
            }
        }
// Divide pattern common vector by nObs
        bmat.divideByScalar((double) nObs.getValue()) ;

        return (rc) ;
    }

    public static int myV( MyMatrix bmat, MyMatrix vmat, lengthy firstObs,
        lengthy lastObs, int nVariables, MyLong nObs) {

        int      rc, varIndex  ;
        MyMatrix emat ;
        double   worth ;
        String   msg ;

        rc = 0 ;
// Create and initialized vector for commentary degree errors
        emat = new MyMatrix(1, nVariables);
// Loop over observations
        for(lengthy obs=firstObs; obs<=lastObs; obs++) {
            if (!Information.isParsedIfTrue(obs)) {
                proceed;
            }

// Loop over variables
            for(int var = 1; var<=nVariables; var++) {
// get the actual variable index for parsed variable -var-
                varIndex = Information.mapParsedVarIndex(var);
// Put worth of commentary obs on variable varIndex into worth
                worth    = Information.getNum(varIndex, obs);

                if (Information.isValueMissing(worth)) {
                    msg = "{err}lacking values encountered" ;
                    SFIToolkit.errorln(msg);
                    return(416) ;
                }
                emat.storeValue(0, (var-1), bmat.getValue(0,(var-1)) - worth) ;
            }

            for(int j = 0; j

MyCalsW.myAve() is a Java implementation of the Mata perform MyAve(), mentioned in Programming an estimation command in Stata: Making ready to jot down a plugin. It places the pattern averages into the bmat occasion of the MyMatrix class, and it places the variety of observations within the pattern into nObs. A lot of the code for this technique is normal Java or makes use of SFI strategies that I've already mentioned. Traces 18, 34, and 38 deserve remark.

Line 18 of MyCalcsW.java makes use of the tactic incrementValue() of MyLong to increment the variety of observations saved in nObs. It increments the present worth of nObs by one.

Line 34 makes use of the incrementByValue() technique of MyMatrix. When calculating the pattern common and storing it within the jth factor of a vector named b, one must retailer b[j] + worth into b[j]. In different phrases, one increments the quantity of the jth factor in b by worth. bmat.incrementByValue(0,var-1, worth) increments the factor var-1 in bmat by worth.

Line 38 makes use of the divideByScalar() technique of MyMatrix. bmat.divideByScalar(z) replaces every factor of bmat with that factor divided by the quantity z.

MyCalsW.myV() is a Java implementation of the Mata perform MyV(), mentioned in Programming an estimation command in Stata: Making ready to jot down a plugin. It places the VCE into the vmat occasion of the MyMatrix class. A lot of the code for this technique is normal Java or makes use of strategies that I've already mentioned. Traces 72, 77, and 85 use the MyMatrix strategies storevalue() and getValue(). vmat.storeValue(i, j, z) shops the worth z into factor (i, j) of the vmat occasion of MyMatrix. vmat.getValue(i, j) returns the worth saved in factor (i, j) of the vmat occasion of MyMatrix.

Performed and undone

I confirmed the right way to implement a Java plugin that does the calculations carried out by Mata work features in mymean10.ado and mymean11.ado, as mentioned in Programming an estimation command in Stata: Making ready to jot down a plugin.

Thanks

Because of James Hassell of StataCorp for sharing a few of his Java information and expertise.



Related Articles

Latest Articles