Example usage for org.apache.commons.math3.complex Complex abs

List of usage examples for org.apache.commons.math3.complex Complex abs

Introduction

In this page you can find the example usage for org.apache.commons.math3.complex Complex abs.

Prototype

public double abs() 

Source Link

Document

Return the absolute value of this complex number.

Usage

From source file:com.fpuna.preproceso.TestApacheMathLibDemo.java

/**
 * @param args// w  w w .  ja v  a2s.c  o m
 */
public static void main(String[] args) {

    RandomGenerator randomGenerator = new JDKRandomGenerator();
    System.out.println(randomGenerator.nextInt());
    System.out.println(randomGenerator.nextDouble());

    /**
     * Descriptive Statistics like MEAN,GP,SD,MAX
    *
     */
    DescriptiveStatistics stats = new DescriptiveStatistics();
    stats.addValue(1);
    stats.addValue(2);
    stats.addValue(3);
    stats.addValue(4);
    stats.addValue(5);
    stats.addValue(6);
    stats.addValue(7);
    System.out.print("Mean : " + stats.getMean() + "\n");
    System.out.print("Standard deviation : " + stats.getStandardDeviation() + "\n");
    System.out.print("Max : " + stats.getMax() + "\n");

    /**
     * Complex number format a+bi
    *
     */
    Complex c1 = new Complex(1, 2);
    Complex c2 = new Complex(2, 3);
    System.out.print("Absolute of c1 " + c1.abs() + "\n");
    System.out.print("Addition : " + (c1.add(c2)) + "\n");
}

From source file:mandelbrot.MainDraw.java

public static int iterate(Complex c) {
    Complex z = new Complex(0, 0);
    int i;//w ww.  ja  va 2 s.c o m
    for (i = 0; i < 800; i++) {
        //Complex pz = z;
        z = mandelFunction(z, c);
        if (z.abs() > 2) {
            return i;
        }
    }
    return i;
}

From source file:eu.itesla_project.iidm.ddb.eurostag.model.TransformerModel.java

public StateVariable toSv2(StateVariable sv1) {
    Complex s1 = new Complex(-sv1.p, -sv1.q); // s1=p1+jq1
    Complex u1 = ComplexUtils.polar2Complex(sv1.u, Math.toRadians(sv1.theta));
    Complex v1 = u1.divide(SQUARE_3); // v1=u1/sqrt(3)
    Complex v1p = v1.multiply(ratio); // v1p=v1*rho
    Complex i1 = s1.divide(v1.multiply(3)).conjugate(); // i1=conj(s1/(3*v1))
    Complex i1p = i1.divide(ratio); // i1p=i1/rho
    Complex i2 = i1p.subtract(y.multiply(v1p)).negate(); // i2=-(i1p-y*v1p)
    Complex v2 = v1p.subtract(z.multiply(i2)); // v2=v1p-z*i2
    Complex s2 = v2.multiply(3).multiply(i2.conjugate()); // s2=3*v2*conj(i2)
    Complex u2 = v2.multiply(SQUARE_3);
    return new StateVariable(-s2.getReal(), -s2.getImaginary(), u2.abs(), Math.toDegrees(u2.getArgument()));
}

From source file:eu.itesla_project.iidm.ddb.eurostag.model.TransformerModel.java

public StateVariable toSv1(StateVariable sv2) {
    Complex s2 = new Complex(-sv2.p, -sv2.q); // s2=p2+jq2
    Complex u2 = ComplexUtils.polar2Complex(sv2.u, Math.toRadians(sv2.theta));
    Complex v2 = u2.divide(SQUARE_3); // v2=u2/sqrt(3)
    Complex i2 = s2.divide(v2.multiply(3)).conjugate(); // i2=conj(s2/(3*v2))
    Complex v1p = v2.add(z.multiply(i2)); // v1'=v2+z*i2
    Complex i1p = i2.negate().add(y.multiply(v1p)); // i1'=-i2+v1'*y
    Complex i1 = i1p.multiply(ratio); // i1=i1p*ration
    Complex v1 = v1p.divide(ratio); // v1=v1p/ration
    Complex s1 = v1.multiply(3).multiply(i1.conjugate()); // s1=3*v1*conj(i1)
    Complex u1 = v1.multiply(SQUARE_3);
    return new StateVariable(-s1.getReal(), -s1.getImaginary(), u1.abs(), Math.toDegrees(u1.getArgument()));
}

From source file:eu.itesla_project.iidm.network.util.SV.java

public SV otherSide(float r, float x, float g, float b, float ratio) {
    Complex z = new Complex(r, x); // z=r+jx
    Complex y = new Complex(g, b); // y=g+jb
    Complex s1 = new Complex(p, q); // s1=p1+jq1
    Complex u1 = ComplexUtils.polar2Complex(u, Math.toRadians(a));
    Complex v1 = u1.divide(Math.sqrt(3f)); // v1=u1/sqrt(3)

    Complex v1p = v1.multiply(ratio); // v1p=v1*rho
    Complex i1 = s1.divide(v1.multiply(3)).conjugate(); // i1=conj(s1/(3*v1))
    Complex i1p = i1.divide(ratio); // i1p=i1/rho
    Complex i2 = i1p.subtract(y.multiply(v1p)); // i2=i1p-y*v1p
    Complex v2 = v1p.subtract(z.multiply(i2)); // v2=v1p-z*i2
    Complex s2 = v2.multiply(3).multiply(i2.conjugate()); // s2=3*v2*conj(i2)

    Complex u2 = v2.multiply(Math.sqrt(3f));
    return new SV((float) -s2.getReal(), (float) -s2.getImaginary(), (float) u2.abs(),
            (float) Math.toDegrees(u2.getArgument()));
}

From source file:com.wwidesigner.modelling.DefaultInstrumentCalculator.java

@Override
public double calcGain(double freq, Complex Z) {
    // Magnitude of loop gain for a given note, after Auvray, 2012.
    // Loop gain G = gainFactor * freq * rho / abs(Z).

    Double G0 = instrument.getMouthpiece().getGainFactor();
    if (G0 == null) {
        return 1.0;
    }//from ww w. java 2 s  .  co m
    double gain = (G0 * freq * params.getRho()) / Z.abs();
    return gain;
}

From source file:com.autsia.bracer.BracerParser.java

/**
 * Evaluates once parsed math expression with "var" variable included
 *
 * @param variableValue User-specified <code>Double</code> value
 * @return <code>String</code> representation of the result
 * @throws <code>ParseException</code> if the input expression is not
 *                                     correct
 * @since 3.0/*from  w  ww  .  ja v a2 s . c  o m*/
 */
public String evaluate(double variableValue) throws ParseException {
    /* check if is there something to evaluate */
    if (stackRPN.empty()) {
        return "";
    }

    /* clean answer stack */
    stackAnswer.clear();

    /* get the clone of the RPN stack for further evaluating */
    @SuppressWarnings("unchecked")
    Stack<String> stackRPN = (Stack<String>) this.stackRPN.clone();

    /* enroll the variable value into expression */
    Collections.replaceAll(stackRPN, VARIABLE, Double.toString(variableValue));

    /* evaluating the RPN expression */
    while (!stackRPN.empty()) {
        String token = stackRPN.pop();
        if (isNumber(token)) {
            stackAnswer.push(token);
        } else if (isOperator(token)) {
            Complex a = complexFormat.parse(stackAnswer.pop());
            Complex b = complexFormat.parse(stackAnswer.pop());
            boolean aBoolean = a.getReal() == 1.0;
            boolean bBoolean = b.getReal() == 1.0;
            switch (token) {
            case "+":
                stackAnswer.push(complexFormat.format(b.add(a)));
                break;
            case "-":
                stackAnswer.push(complexFormat.format(b.subtract(a)));
                break;
            case "*":
                stackAnswer.push(complexFormat.format(b.multiply(a)));
                break;
            case "/":
                stackAnswer.push(complexFormat.format(b.divide(a)));
                break;
            case "|":
                stackAnswer.push(String.valueOf(aBoolean || bBoolean ? "1" : "0"));
                break;
            case "&":
                stackAnswer.push(String.valueOf(aBoolean && bBoolean ? "1" : "0"));
                break;
            }
        } else if (isFunction(token)) {
            Complex a = complexFormat.parse(stackAnswer.pop());
            boolean aBoolean = a.getReal() == 1.0;
            switch (token) {
            case "abs":
                stackAnswer.push(complexFormat.format(a.abs()));
                break;
            case "acos":
                stackAnswer.push(complexFormat.format(a.acos()));
                break;
            case "arg":
                stackAnswer.push(complexFormat.format(a.getArgument()));
                break;
            case "asin":
                stackAnswer.push(complexFormat.format(a.asin()));
                break;
            case "atan":
                stackAnswer.push(complexFormat.format(a.atan()));
                break;
            case "conj":
                stackAnswer.push(complexFormat.format(a.conjugate()));
                break;
            case "cos":
                stackAnswer.push(complexFormat.format(a.cos()));
                break;
            case "cosh":
                stackAnswer.push(complexFormat.format(a.cosh()));
                break;
            case "exp":
                stackAnswer.push(complexFormat.format(a.exp()));
                break;
            case "imag":
                stackAnswer.push(complexFormat.format(a.getImaginary()));
                break;
            case "log":
                stackAnswer.push(complexFormat.format(a.log()));
                break;
            case "neg":
                stackAnswer.push(complexFormat.format(a.negate()));
                break;
            case "real":
                stackAnswer.push(complexFormat.format(a.getReal()));
                break;
            case "sin":
                stackAnswer.push(complexFormat.format(a.sin()));
                break;
            case "sinh":
                stackAnswer.push(complexFormat.format(a.sinh()));
                break;
            case "sqrt":
                stackAnswer.push(complexFormat.format(a.sqrt()));
                break;
            case "tan":
                stackAnswer.push(complexFormat.format(a.tan()));
                break;
            case "tanh":
                stackAnswer.push(complexFormat.format(a.tanh()));
                break;
            case "pow":
                Complex b = complexFormat.parse(stackAnswer.pop());
                stackAnswer.push(complexFormat.format(b.pow(a)));
                break;
            case "not":
                stackAnswer.push(String.valueOf(!aBoolean ? "1" : "0"));
                break;
            }
        }
    }

    if (stackAnswer.size() > 1) {
        throw new ParseException("Some operator is missing", 0);
    }

    return stackAnswer.pop();
}

From source file:com.calc.BracerParser.java

/**
 * Evaluates once parsed math expression with "var" variable included
 *
 * @param variableValue User-specified <code>Double</code> value
 * @return <code>String</code> representation of the result
 * @throws <code>ParseException</code> if the input expression is not
 *                                     correct
 * @since 3.0/*from www. ja  va2s .c om*/
 */
public String evaluate(double variableValue) throws ParseException {
    /* check if is there something to evaluate */
    if (stackRPN.empty()) {
        return "";
    }

    /* clean answer stack */
    stackAnswer.clear();

    /* get the clone of the RPN stack for further evaluating */
    @SuppressWarnings("unchecked")
    Stack<String> stackRPN = (Stack<String>) this.stackRPN.clone();

    /* enroll the variable value into expression */
    Collections.replaceAll(stackRPN, VARIABLE, Double.toString(variableValue));

    /* evaluating the RPN expression */
    while (!stackRPN.empty()) {
        String token = stackRPN.pop();
        if (isNumber(token)) {
            stackAnswer.push(token);
        } else if (isOperator(token)) {
            Complex a = complexFormat.parse(stackAnswer.pop());
            Complex b = complexFormat.parse(stackAnswer.pop());
            boolean aBoolean = a.getReal() == 1.0;
            boolean bBoolean = b.getReal() == 1.0;
            switch (token) {
            case "+":
                stackAnswer.push(complexFormat.format(b.add(a)));
                break;
            case "-":
                stackAnswer.push(complexFormat.format(b.subtract(a)));
                break;
            case "*":
                stackAnswer.push(complexFormat.format(b.multiply(a)));
                break;
            case "/":
                stackAnswer.push(complexFormat.format(b.divide(a)));
                break;
            case "|":
                stackAnswer.push(String.valueOf(aBoolean || bBoolean ? "1" : "0"));
                break;
            case "&":
                stackAnswer.push(String.valueOf(aBoolean && bBoolean ? "1" : "0"));
                break;
            }
        } else if (isFunction(token)) {
            Complex a = complexFormat.parse(stackAnswer.pop());
            boolean aBoolean = a.getReal() == 1.0;
            switch (token) {
            case "fat":
                stackAnswer.push(complexFormat.format(a.abs()));
                break;
            case "fib":
                stackAnswer.push(complexFormat.format(a.acos()));
                break;
            case "arg":
                stackAnswer.push(complexFormat.format(a.getArgument()));
                break;
            case "asin":
                stackAnswer.push(complexFormat.format(a.asin()));
                break;
            case "atan":
                stackAnswer.push(complexFormat.format(a.atan()));
                break;
            case "conj":
                stackAnswer.push(complexFormat.format(a.conjugate()));
                break;
            case "cos":
                stackAnswer.push(complexFormat.format(a.cos()));
                break;
            case "cosh":
                stackAnswer.push(complexFormat.format(a.cosh()));
                break;
            case "exp":
                stackAnswer.push(complexFormat.format(a.exp()));
                break;
            case "imag":
                stackAnswer.push(complexFormat.format(a.getImaginary()));
                break;
            case "log":
                stackAnswer.push(complexFormat.format(a.log()));
                break;
            case "neg":
                stackAnswer.push(complexFormat.format(a.negate()));
                break;
            case "real":
                stackAnswer.push(complexFormat.format(a.getReal()));
                break;
            case "sin":
                stackAnswer.push(complexFormat.format(a.sin()));
                break;
            case "sinh":
                stackAnswer.push(complexFormat.format(a.sinh()));
                break;
            case "sqrt":
                stackAnswer.push(complexFormat.format(a.sqrt()));
                break;
            case "tan":
                stackAnswer.push(complexFormat.format(a.tan()));
                break;
            case "tanh":
                stackAnswer.push(complexFormat.format(a.tanh()));
                break;
            case "pow":
                Complex b = complexFormat.parse(stackAnswer.pop());
                stackAnswer.push(complexFormat.format(b.pow(a)));
                break;
            case "not":
                stackAnswer.push(String.valueOf(!aBoolean ? "1" : "0"));
                break;
            }
        }
    }

    if (stackAnswer.size() > 1) {
        throw new ParseException("Some operator is missing", 0);
    }

    return stackAnswer.pop();
}

From source file:gov.pnnl.goss.gridappsd.data.handlers.CIMDataRDFToGLM.java

public void process(String args[]) throws UnsupportedEncodingException, FileNotFoundException {

    String fName = "", fOut = "", fBus = "", fEnc = "";
    double freq = 60.0, vmult = 0.001, smult = 0.001, load_scale = 1.0;
    int fInFile = 0;
    int fNameSeq = 0;
    boolean bWantSched = false, bWantZIP = false;
    boolean bWantSec = true;
    String fSched = "";
    double Zcoeff = 0.0, Icoeff = 0.0, Pcoeff = 0.0;

    if (args.length < 3) {
        System.out.println("Usage: CDPSM_to_GLM [options] input.xml output_root");
        System.out.println("          -l={1}                   // load scaling factor, defaults to 1");
        System.out.println("          -t={y|n}                // triplex; y/n to include secondary");
        System.out.println("          -e={u|i}                // encoding; UTF-8 or ISO-8859-1");
        System.out.println("          -f={50|60}             // system frequency");
        System.out.println(/*from  w  w  w. j  a  v  a 2  s .co  m*/
                "          -v={1|0.001}          // multiplier that converts voltage to V for GridLAB-D");
        System.out
                .println("          -s={1000|1|0.001}  // multiplier that converts p,q,s to VA for GridLAB-D");
        System.out.println("          -q={y|n}                // are unique names used?");
        System.out.println(
                "          -n={schedule_name} // root filename for scheduled ZIP loads (defaults to none)");
        System.out.println(
                "          -z={0..1}              // constant Z portion (defaults to 0 for CIM-defined");
        System.out.println(
                "          -i={0..1}              // constant I portion (defaults to 0 for CIM-defined");
        System.out.println(
                "          -p={0..1}              // constant P portion (defaults to 0 for CIM-defined");
    }
    int i = 0;
    while (i < args.length) {
        if (args[i].charAt(0) == '-') {
            char opt = args[i].charAt(1);
            String optVal = args[i].substring(3);
            if (opt == 't') {
                if (optVal.charAt(0) == 'n') {
                    bWantSec = false;
                }
            } else if (opt == 'e') {
                if (optVal.charAt(0) == 'u') {
                    fEnc = "UTF8";
                } else {
                    fEnc = "ISO-8859-1";
                }
            } else if (opt == 'q') {
                if (optVal.charAt(0) == 'y') {
                    fNameSeq = 0;
                } else {
                    fNameSeq = 1;
                }
            } else if (opt == 'l') {
                load_scale = Double.parseDouble(optVal);
            } else if (opt == 'f') {
                freq = Double.parseDouble(optVal);
            } else if (opt == 'v') {
                vmult = Double.parseDouble(optVal);
            } else if (opt == 's') {
                smult = Double.parseDouble(optVal);
            } else if (opt == 'n') {
                fSched = optVal;
                bWantSched = true;
            } else if (opt == 'z') {
                Zcoeff = Double.parseDouble(optVal);
                bWantZIP = true;
            } else if (opt == 'i') {
                Icoeff = Double.parseDouble(optVal);
                bWantZIP = true;
            } else if (opt == 'p') {
                Pcoeff = Double.parseDouble(optVal);
                bWantZIP = true;
            }
        } else if (fInFile < 1) {
            fInFile = 1;
            fName = args[i];
        } else {
            fOut = args[i] + "_base.glm";
            fBus = args[i] + "_busxy.glm";
        }
        ++i;
    }

    System.out.println(fEnc + " f=" + String.format("%6g", freq) + " v=" + String.format("%6g", vmult) + " s="
            + String.format("%6g", smult));

    Model model = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM);

    InputStream in = FileManager.get().open(fName);
    if (in == null) {
        throw new IllegalArgumentException("File: " + fName + " not found");
    }

    PrintWriter out = new PrintWriter(fOut);
    PrintWriter outBus = new PrintWriter(fBus);

    model.read(new InputStreamReader(in, fEnc), baseURI, "RDF/XML");

    System.out.println("***** XML has been read *****");

    String qPrefix = "PREFIX r: <" + nsRDF + "> PREFIX c: <" + nsCIM + "> ";
    Query query;
    QueryExecution qexec;
    ResultSet results;
    QuerySolution soln;
    Resource res;
    String id, name, phs, bus1, bus2;
    boolean phs_delta;
    Property ptName = model.getProperty(nsCIM, "IdentifiedObject.name");
    Property ptType = model.getProperty(nsRDF, "type");
    Property ptOpen = model.getProperty(nsCIM, "Switch.normalOpen");

    Property ptEqBaseV = model.getProperty(nsCIM, "ConductingEquipment.BaseVoltage");
    Property ptLevBaseV = model.getProperty(nsCIM, "VoltageLevel.BaseVoltage");
    Property ptEquip = model.getProperty(nsCIM, "Equipment.EquipmentContainer");
    Property ptBaseNomV = model.getProperty(nsCIM, "BaseVoltage.nominalVoltage");

    // Dump all the GeoLocation references
    /*
    Property ptGeo = model.getProperty (nsCIM, "PowerSystemResource.GeoLocation");
    query = QueryFactory.create (qPrefix + "select ?s where {?s r:type c:GeoLocation}");
    qexec = QueryExecutionFactory.create (query, model);
    results=qexec.execSelect();
    while (results.hasNext()) {
       soln = results.next();
       id = soln.get ("?s").toString();
       res = model.getResource (id);
       name = SafeResName (res, ptName);
       ResIterator it = model.listResourcesWithProperty (ptGeo, res);
       while (it.hasNext()) {
    Resource rEq = it.nextResource();
    String sType = rEq.getProperty(ptType).getObject().toString();
    outBus.println ("// " + name + "==>" + sType + ":" + SafeResName(rEq, ptName));
       }
    }
    outBus.println ();
    */

    // ConnectivityNode ==> bus coordinate CSV 
    query = QueryFactory.create(qPrefix + "select ?s where {?s r:type c:ConnectivityNode}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    while (results.hasNext()) {
        soln = results.next();
        id = soln.get("?s").toString();
        res = model.getResource(id);
        name = GldPrefixedNodeName(SafeResName(res, ptName));
        String strPos = GetBusPositionString(model, id);
        if (strPos.length() > 0) {
            outBus.println("\"" + name + "\", " + strPos);
        } else {
            outBus.println("// " + name + ", *****");
        }
        mapNodes.put(name, new GldNode(name));
    }
    outBus.println();
    outBus.close();

    // EnergySource ==> Circuit
    int NumCircuits = 0;
    int NumSources = 0;

    query = QueryFactory.create(qPrefix + "select ?s ?name ?v ?ckt where {?s r:type c:EnergySource. "
            + "?s c:IdentifiedObject.name ?name;" + "    c:EnergySource.voltageMagnitude ?v;"
            + "    c:Equipment.EquipmentContainer ?ckt" + "}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    Property ptESr0 = model.getProperty(nsCIM, "EnergySource.r0");
    Property ptESr1 = model.getProperty(nsCIM, "EnergySource.r");
    Property ptESx0 = model.getProperty(nsCIM, "EnergySource.x0");
    Property ptESx1 = model.getProperty(nsCIM, "EnergySource.x");
    Property ptESVnom = model.getProperty(nsCIM, "EnergySource.nominalVoltage");
    Property ptESVmag = model.getProperty(nsCIM, "EnergySource.voltageMagnitude");
    Property ptESVang = model.getProperty(nsCIM, "EnergySource.voltageAngle");
    while (results.hasNext()) {
        soln = results.next();
        ++NumSources;

        id = soln.get("?s").toString();
        name = GLD_Name(soln.get("?name").toString(), false);
        String vSrce = soln.get("?v").toString();
        String ckt = soln.get("?ckt").toString();

        res = model.getResource(id);

        double vmag = vmult * SafeDouble(res, ptESVmag, 1.0);
        double vnom = vmult * SafeDouble(res, ptESVnom, vmag);
        double vang = SafeDouble(res, ptESVang, 0.0) * 57.3;
        double r0 = SafeDouble(res, ptESr0, 0.0);
        double r1 = SafeDouble(res, ptESr1, 0.0);
        double x1 = SafeDouble(res, ptESx1, 0.001);
        double x0 = SafeDouble(res, ptESx0, x1);
        double vpu = vmag / vnom;

        bus1 = GetBusName(model, id, 1); // TODO - no phase model

        String srcClass = "Vsource.";
        if (NumCircuits < 1) { // name.equals ("source")
            srcClass = "Circuit.";
            name = GLD_Name(GetPropValue(model, ckt, "IdentifiedObject.name"), false);
            GldNode nd = mapNodes.get(bus1);
            nd.bSwing = true;
            NumCircuits = 1;
        } else if (name.equals("source")) {
            name = "_" + name;
        }
    }
    if (NumCircuits < 1) { // try the first breaker
        query = QueryFactory.create(qPrefix + "select ?s where {?s r:type c:Breaker}");
        qexec = QueryExecutionFactory.create(query, model);
        results = qexec.execSelect();
        while (results.hasNext()) {
            soln = results.next();
            id = soln.get("?s").toString();

            res = model.getResource(id);
            bus1 = GetBusName(model, id, 1);
            GldNode nd = mapNodes.get(bus1);
            nd.bSwing = true;

            name = SafeResName(res, ptName);
            //            out.println ("new Circuit." + name + " phases=3 bus1=" + bus1 + " basekv=1");
        }
    }

    //      out.println ("// set frequency=" + String.format("%6g", freq));

    // SynchronousMachine ==> Generator
    out.println();
    query = QueryFactory.create(qPrefix + "select ?s where {?s r:type c:SynchronousMachine}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    Property ptGenS = model.getProperty(nsCIM, "GeneratingUnit.ratedNetMaxP");
    Property ptGenP = model.getProperty(nsCIM, "GeneratingUnit.initialP");
    Property ptGenRef = model.getProperty(nsCIM, "SynchronousMachine.GeneratingUnit");
    Property ptGenQ = model.getProperty(nsCIM, "SynchronousMachine.baseQ");
    Property ptGenQmin = model.getProperty(nsCIM, "SynchronousMachine.minQ");
    Property ptGenQmax = model.getProperty(nsCIM, "SynchronousMachine.maxQ");
    while (results.hasNext()) {
        soln = results.next();

        id = soln.get("?s").toString();

        res = model.getResource(id);
        // TODO - generators need phase modeling as well
        bus1 = GetBusName(model, id, 1);
        name = SafeResName(res, ptName);
        Resource resUnit = res.getProperty(ptGenRef).getResource();

        double genS = SafeDouble(resUnit, ptGenS, 1.0) * 1000.0; // assume MW per CPSM
        double genP = SafeDouble(resUnit, ptGenP, 1.0) * 1000.0;
        double genQ = SafeDouble(res, ptGenQ, 0.0) * 1000.0;
        double genQmin = SafeDouble(res, ptGenQmin, 0.44 * genS) * 1000.0 * -1.0;
        double genQmax = SafeDouble(res, ptGenQmax, 0.44 * genS) * 1000.0;
        double genKv = vmult * FindBaseVoltage(res, ptEquip, ptEqBaseV, ptLevBaseV, ptBaseNomV);

        //         out.println ("new Generator." + name + " phases=3 bus1=" + bus1 + 
        //                            " conn=w kva=" + String.format("%6g", genS) + " kw=" + String.format("%6g", genP) + 
        //                            " kvar=" + String.format("%6g", genQ) + " minkvar=" + String.format("%6g", genQmin) + 
        //                            " maxkvar=" + String.format("%6g", genQmax) + " kv=" + String.format("%6g", genKv));
    }

    // EnergyConsumer ==> Load
    double total_load_w = 0.0;
    out.println();
    query = QueryFactory.create(qPrefix + "select ?s where {?s r:type c:EnergyConsumer}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    Property ptP = model.getProperty(nsCIM, "EnergyConsumer.pfixed");
    Property ptQ = model.getProperty(nsCIM, "EnergyConsumer.qfixed");
    Property ptCust = model.getProperty(nsCIM, "EnergyConsumer.customerCount");
    Property ptPhsLoad1 = model.getProperty(nsCIM, "EnergyConsumerPhase.EnergyConsumer");
    Property ptPhsLoad2 = model.getProperty(nsCIM, "EnergyConsumerPhase.phase");
    Property ptConnLoad = model.getProperty(nsCIM, "EnergyConsumer.phaseConnection");
    Property ptResponse = model.getProperty(nsCIM, "EnergyConsumer.LoadResponse");
    Property ptPv = model.getProperty(nsCIM, "LoadResponseCharacteristic.pVoltageExponent");
    Property ptQv = model.getProperty(nsCIM, "LoadResponseCharacteristic.qVoltageExponent");
    Property ptPz = model.getProperty(nsCIM, "LoadResponseCharacteristic.pConstantImpedance");
    Property ptPi = model.getProperty(nsCIM, "LoadResponseCharacteristic.pConstantCurrent");
    Property ptPp = model.getProperty(nsCIM, "LoadResponseCharacteristic.pConstantPower");
    Property ptQz = model.getProperty(nsCIM, "LoadResponseCharacteristic.qConstantImpedance");
    Property ptQi = model.getProperty(nsCIM, "LoadResponseCharacteristic.qConstantCurrent");
    Property ptQp = model.getProperty(nsCIM, "LoadResponseCharacteristic.qConstantPower");
    while (results.hasNext()) {
        soln = results.next();

        id = soln.get("?s").toString();

        res = model.getResource(id);
        phs = WirePhases(model, res, ptPhsLoad1, ptPhsLoad2);
        phs_delta = Shunt_Delta(res, ptConnLoad);
        bus1 = GetBusName(model, id, 1);

        name = SafeResName(res, ptName); // not used as a parameter
        double pL = smult * SafeDouble(res, ptP, 1);
        double qL = smult * SafeDouble(res, ptQ, 0);
        total_load_w += pL;
        double Pp = 100, Qp = 100;
        double Pv = 0, Qv = 0, Pz = 0, Qz = 0, Pi = 0, Qi = 0;
        if (res.hasProperty(ptResponse)) {
            Resource rModel = res.getProperty(ptResponse).getResource();
            Pv = SafeDouble(rModel, ptPv, 0);
            Qv = SafeDouble(rModel, ptQv, 0);
            Pz = SafeDouble(rModel, ptPz, 0);
            Pi = SafeDouble(rModel, ptPi, 0);
            Pp = SafeDouble(rModel, ptPp, 0);
            Qz = SafeDouble(rModel, ptQz, 0);
            Qi = SafeDouble(rModel, ptQi, 0);
            Qp = SafeDouble(rModel, ptQp, 0);
        }

        GldNode nd = mapNodes.get(bus1);
        nd.nomvln = FindBaseVoltage(res, ptEquip, ptEqBaseV, ptLevBaseV, ptBaseNomV) / Math.sqrt(3.0);
        nd.bDelta = phs_delta;
        // accumulate P and Q by phase first, and only then update the node phases
        AccumulateLoads(nd, phs, pL, qL, Pv, Qv, Pz, Pi, Pp, Qz, Qi, Qp);
    }

    // LinearShuntCompensator ==> Capacitor
    out.println();
    query = QueryFactory.create(qPrefix + "select ?s ?name where {?s r:type c:LinearShuntCompensator. "
            + "?s c:IdentifiedObject.name ?name}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    Property ptSecB = model.getProperty(nsCIM, "LinearShuntCompensator.bPerSection");
    Property ptSecN = model.getProperty(nsCIM, "LinearShuntCompensator.normalSections");
    Property ptNumSteps = model.getProperty(nsCIM, "ShuntCompensator.maximumSections");
    Property ptPhsShunt1 = model.getProperty(nsCIM, "ShuntCompensatorPhase.ShuntCompensator");
    Property ptPhsShunt2 = model.getProperty(nsCIM, "ShuntCompensatorPhase.phase");
    Property ptConnShunt = model.getProperty(nsCIM, "ShuntCompensator.phaseConnection");
    Property ptAVRDelay = model.getProperty(nsCIM, "ShuntCompensator.aVRDelay");
    Property ptNomU = model.getProperty(nsCIM, "ShuntCompensator.nomU");
    Property ptCapCtl = model.getProperty(nsCIM, "RegulatingControl.RegulatingCondEq");

    while (results.hasNext()) {
        soln = results.next();

        id = soln.get("?s").toString();
        name = GLD_Name(soln.get("?name").toString(), false);
        res = model.getResource(id);
        phs = WirePhases(model, res, ptPhsShunt1, ptPhsShunt2);
        phs_delta = Shunt_Delta(res, ptConnShunt);
        bus1 = GetBusName(model, id, 1);
        GldNode nd = mapNodes.get(bus1);
        nd.nomvln = FindBaseVoltage(res, ptEquip, ptEqBaseV, ptLevBaseV, ptBaseNomV) / Math.sqrt(3.0);
        nd.AddPhases(phs);

        double cap_b = SafeInt(res, ptNumSteps, 1) * SafeDouble(res, ptSecB, 0.0001);
        double cap_v = SafeDouble(res, ptNomU, 120.0);
        double cap_q = cap_v * cap_v * cap_b;
        cap_q /= phs.length();
        if (phs.length() > 1 && !phs_delta)
            cap_v /= Math.sqrt(3.0);

        out.println("object capacitor {");
        out.println("   name \"cap_" + name + "\";");
        out.println("   parent \"" + bus1 + "\";");
        if (phs_delta) {
            out.println("  phases " + phs + "D;");
            out.println("  phases_connected " + phs + "D;");
        } else {
            out.println("  phases " + phs + "N;");
            out.println("  phases_connected " + phs + "N;");
        }
        out.println("   cap_nominal_voltage " + String.format("%6g", cap_v) + ";");
        if (phs.contains("A")) {
            out.println("  capacitor_A " + String.format("%6g", cap_q) + ";");
            out.println("  switchA CLOSED;");
        }
        if (phs.contains("B")) {
            out.println("  capacitor_B " + String.format("%6g", cap_q) + ";");
            out.println("  switchB CLOSED;");
        }
        if (phs.contains("C")) {
            out.println("  capacitor_C " + String.format("%6g", cap_q) + ";");
            out.println("  switchC CLOSED;");
        }

        // see if we have capacitor control settings
        ResIterator itCtl = model.listResourcesWithProperty(ptCapCtl, res);
        if (itCtl.hasNext()) {
            out.println(GetCapControlData(model, res, itCtl.nextResource()));
            double delay = SafeDouble(res, ptAVRDelay, 10.0);
            out.println("   dwell_time " + String.format("%6g", delay) + ";");
        }

        out.println("}");
    }

    // for GridLAB-D, we need to write the transformers first so that we can identify
    // the secondary nodes and carry primary phasing down to them
    // Transformer Codes
    out.println();
    query = QueryFactory.create(qPrefix + "select ?s ?name where {?s r:type c:TransformerTankInfo. "
            + "?s c:IdentifiedObject.name ?name" + "}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    while (results.hasNext()) {
        soln = results.next();

        id = soln.get("?s").toString();
        name = GLD_Name(soln.get("?name").toString(), false);
        String s = GetXfmrCode(model, id, smult, vmult, bWantSec);
        if (s.length() > 0) {
            out.println(s);
        }
    }

    // Transformers
    out.println();
    query = QueryFactory.create(qPrefix + "select ?s ?name where {?s r:type c:PowerTransformer. "
            + "?s c:IdentifiedObject.name ?name" + "}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    while (results.hasNext()) {
        soln = results.next();

        id = soln.get("?s").toString();
        name = GLD_Name(soln.get("?name").toString(), false);
        res = model.getResource(id);

        Property ptTank = model.getProperty(nsCIM, "TransformerTank.PowerTransformer");
        ResIterator itTank = model.listResourcesWithProperty(ptTank, res);
        if (itTank.hasNext()) { // write all the tanks to this bank
            String s = GetPowerTransformerTanks(model, res, itTank, bWantSec);
            if (s.length() > 0) {
                out.println(s);
            }
        } else { // standalone power transformer
            out.println(GetPowerTransformerData(model, res));
        }
    }

    // WireData
    out.println();
    query = QueryFactory.create(qPrefix + "select ?s where {?s r:type c:OverheadWireInfo}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    while (results.hasNext()) {
        soln = results.next();

        id = soln.get("?s").toString();
        res = model.getResource(id);
        name = SafeResName(res, ptName);

        //         out.println ("new WireData." + name  + GetWireData (model, res));
    }

    // TSData
    out.println();
    query = QueryFactory.create(qPrefix + "select ?s where {?s r:type c:TapeShieldCableInfo}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    Property ptLap = model.getProperty(nsCIM, "TapeShieldCableInfo.tapeLap");
    Property ptThickness = model.getProperty(nsCIM, "TapeShieldCableInfo.tapeThickness");
    Property ptOverScreen = model.getProperty(nsCIM, "CableInfo.diameterOverScreen");
    while (results.hasNext()) {
        soln = results.next();

        id = soln.get("?s").toString();
        res = model.getResource(id);
        name = SafeResName(res, ptName);

        double tapeLap = SafeDouble(res, ptLap, 0.0);
        double tapeThickness = SafeDouble(res, ptThickness, 0.0);
        double dScreen = SafeDouble(res, ptOverScreen, 0.0);

        //         out.println ("new TSData." + name + GetWireData (model, res) + GetCableData (model, res) +
        //                            " DiaShield=" + String.format("%6g", dScreen + 2.0 * tapeThickness) +
        //                            " tapeLayer=" + String.format("%6g", tapeThickness) + " tapeLap=" + String.format("%6g", tapeLap));
    }

    // CNData
    out.println();
    query = QueryFactory.create(qPrefix + "select ?s where {?s r:type c:ConcentricNeutralCableInfo}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    Property ptOverNeutral = model.getProperty(nsCIM, "ConcentricNeutralCableInfo.diameterOverNeutral");
    Property ptStrandCount = model.getProperty(nsCIM, "ConcentricNeutralCableInfo.neutralStrandCount");
    Property ptStrandGmr = model.getProperty(nsCIM, "ConcentricNeutralCableInfo.neutralStrandGmr");
    Property ptStrandRadius = model.getProperty(nsCIM, "ConcentricNeutralCableInfo.neutralStrandRadius");
    Property ptStrandRes = model.getProperty(nsCIM, "ConcentricNeutralCableInfo.neutralStrandRDC20");
    while (results.hasNext()) {
        soln = results.next();

        id = soln.get("?s").toString();
        res = model.getResource(id);
        name = SafeResName(res, ptName);

        double cnDia = SafeDouble(res, ptOverNeutral, 0.0);
        int cnCount = SafeInt(res, ptStrandCount, 0);
        double cnGmr = SafeDouble(res, ptStrandGmr, 0.0);
        double cnRadius = SafeDouble(res, ptStrandRadius, 0.0);
        double cnRes = SafeDouble(res, ptStrandRes, 0.0);

        //         out.println ("new CNData." + name + GetWireData (model, res) + GetCableData (model, res) +
        //                            " k=" + Integer.toString(cnCount) + " GmrStrand=" + String.format("%6g", cnGmr) +
        //                            " DiaStrand=" + String.format("%6g", 2 * cnRadius) + " Rstrand=" + String.format("%6g", cnRes));
    }

    // LineSpacings (LineGeometries were exported as LineSpacings and individual wire assignments
    out.println();
    query = QueryFactory.create(qPrefix + "select ?s ?name where {?s r:type c:WireSpacingInfo. "
            + "?s c:IdentifiedObject.name ?name" + "}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    Property ptWireX = model.getProperty(nsCIM, "WirePosition.xCoord");
    Property ptWireY = model.getProperty(nsCIM, "WirePosition.yCoord");
    Property ptWireP = model.getProperty(nsCIM, "WirePosition.phase");
    Property ptWireS = model.getProperty(nsCIM, "WirePosition.WireSpacingInfo");
    while (results.hasNext()) {
        soln = results.next();

        id = soln.get("?s").toString();
        name = GLD_Name(soln.get("?name").toString(), false);
        res = model.getResource(id);

        int nconds = 0;
        int nphases = 0;
        double wireXa = 0, wireXb = 0, wireXc = 0, wireXn = 0, wireXs1 = 0, wireXs2 = 0;
        double wireYa = 0, wireYb = 0, wireYc = 0, wireYn = 0, wireYs1 = 0, wireYs2 = 0;
        boolean wireA = false;
        boolean wireB = false;
        boolean wireC = false;
        boolean wireN = false;
        boolean wireS1 = false;
        boolean wireS2 = false;
        ResIterator wIter = model.listResourcesWithProperty(ptWireS, res);
        while (wIter.hasNext()) {
            Resource wa = wIter.nextResource();
            ++nconds;
            phs = Phase_Kind_String(wa.getProperty(ptWireP).getObject().toString()); // TODO - protect
            if (phs.equals("A")) {
                wireXa = SafeDouble(wa, ptWireX, 0);
                wireYa = SafeDouble(wa, ptWireY, 0);
                wireA = true;
                ++nphases;
            }
            if (phs.equals("B")) {
                wireXb = SafeDouble(wa, ptWireX, 0);
                wireYb = SafeDouble(wa, ptWireY, 0);
                wireB = true;
                ++nphases;
            }
            if (phs.equals("C")) {
                wireXc = SafeDouble(wa, ptWireX, 0);
                wireYc = SafeDouble(wa, ptWireY, 0);
                wireC = true;
                ++nphases;
            }
            if (phs.equals("N")) {
                wireXn = SafeDouble(wa, ptWireX, 0);
                wireYn = SafeDouble(wa, ptWireY, 0);
                wireN = true;
            }
            if (phs.equals("s1")) {
                wireXs1 = SafeDouble(wa, ptWireX, 0);
                wireYs1 = SafeDouble(wa, ptWireY, 0);
                wireS1 = true;
                ++nphases;
            }
            if (phs.equals("s2")) {
                wireXs2 = SafeDouble(wa, ptWireX, 0);
                wireYs2 = SafeDouble(wa, ptWireY, 0);
                wireS2 = true;
                ++nphases;
            }
        }

        if (nconds > 0 && nphases > 0) {
            mapSpacings.put(name, new SpacingCount(nconds, nphases)); // keep track for wire assignments below
            //            out.println ("new LineSpacing." + name + " nconds=" + Integer.toString(nconds) +
            //                               " nphases=" + Integer.toString(nphases) + " units=m");
            int icond = 0;
            if (wireA) {
                //               out.println ("~ cond=" + Integer.toString(++icond) + 
                //                                  " x=" + String.format("%6g", wireXa) + " h=" + String.format("%6g", wireYa));
            }
            if (wireB) {
                //               out.println ("~ cond=" + Integer.toString(++icond) + 
                //                                  " x=" + String.format("%6g", wireXb) + " h=" + String.format("%6g", wireYb));
            }
            if (wireC) {
                //               out.println ("~ cond=" + Integer.toString(++icond) + 
                //                                  " x=" + String.format("%6g", wireXc) + " h=" + String.format("%6g", wireYc));
            }
            if (wireS1) {
                //               out.println ("~ cond=" + Integer.toString(++icond) + 
                //                                  " x=" + String.format("%6g", wireXs1) + " h=" + String.format("%6g", wireYs1));
            }
            if (wireS2) {
                //               out.println ("~ cond=" + Integer.toString(++icond) + 
                //                                  " x=" + String.format("%6g", wireXs2) + " h=" + String.format("%6g", wireYs2));
            }
            if (wireN) {
                //               out.println ("~ cond=" + Integer.toString(++icond) + 
                //                                  " x=" + String.format("%6g", wireXn) + " h=" + String.format("%6g", wireYn));
            }
        }
    }

    // LineCodes
    int NumLineCodes = 0;
    out.println();
    query = QueryFactory.create(qPrefix + "select ?s ?name where {?s r:type c:PerLengthPhaseImpedance. "
            + "?s c:IdentifiedObject.name ?name" + "}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    while (results.hasNext()) {
        soln = results.next();
        ++NumLineCodes;

        id = soln.get("?s").toString();
        name = GLD_Name(soln.get("?name").toString(), false);
        res = model.getResource(id);
        Property ptCount = model.getProperty(nsCIM, "PerLengthPhaseImpedance.conductorCount");
        if (res.hasProperty(ptCount)) {
            out.println(GetImpedanceMatrix(model, name, ptCount, res, bWantSec));
        }
    }
    query = QueryFactory.create(qPrefix + "select ?s ?name where {?s r:type c:PerLengthSequenceImpedance. "
            + "?s c:IdentifiedObject.name ?name" + "}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    Property ptSeqR1 = model.getProperty(nsCIM, "PerLengthSequenceImpedance.r");
    Property ptSeqR0 = model.getProperty(nsCIM, "PerLengthSequenceImpedance.r0");
    Property ptSeqX1 = model.getProperty(nsCIM, "PerLengthSequenceImpedance.x");
    Property ptSeqX0 = model.getProperty(nsCIM, "PerLengthSequenceImpedance.x0");
    Property ptSeqB1 = model.getProperty(nsCIM, "PerLengthSequenceImpedance.bch");
    Property ptSeqB0 = model.getProperty(nsCIM, "PerLengthSequenceImpedance.b0ch");
    while (results.hasNext()) {
        soln = results.next();
        ++NumLineCodes;

        id = soln.get("?s").toString();
        name = GLD_Name(soln.get("?name").toString(), false);
        res = model.getResource(id);

        double len = 1609.344; // want ohms/mile and nF/mile

        double sqR1 = len * SafeDouble(res, ptSeqR1, 0);
        double sqR0 = len * SafeDouble(res, ptSeqR0, 0);
        double sqX1 = len * SafeDouble(res, ptSeqX1, 0);
        double sqX0 = len * SafeDouble(res, ptSeqX0, 0);
        double sqC1 = len * SafeDouble(res, ptSeqB1, 0) * 1.0e9 / freq / 2.0 / Math.PI;
        double sqC0 = len * SafeDouble(res, ptSeqB0, 0) * 1.0e9 / freq / 2.0 / Math.PI;
        if (sqR0 <= 0) {
            sqR0 = sqR1;
        }
        if (sqX0 <= 0) {
            sqX0 = sqX1;
        }
        out.println(GetSequenceLineConfigurations(name, sqR1, sqX1, sqC1, sqR0, sqX0, sqC0));
    }

    // ACLineSegment ==> Line
    out.println();
    query = QueryFactory.create(qPrefix + "select ?s ?name ?len where {?s r:type c:ACLineSegment. "
            + "?s c:IdentifiedObject.name ?name;" + "    c:Conductor.length ?len" + "}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    Property ptPhsZ = model.getProperty(nsCIM, "ACLineSegment.PerLengthImpedance");
    Property ptLineLen = model.getProperty(nsCIM, "Conductor.length");
    Property ptDataSheet = model.getProperty(nsCIM, "PowerSystemResource.AssetDatasheet");
    Property ptAmps = model.getProperty(nsCIM, "WireInfo.ratedCurrent");
    Property ptPhsLine1 = model.getProperty(nsCIM, "ACLineSegmentPhase.ACLineSegment");
    Property ptPhsLine2 = model.getProperty(nsCIM, "ACLineSegmentPhase.phase");
    while (results.hasNext()) {
        soln = results.next();

        id = soln.get("?s").toString();
        if (fNameSeq > 0) {
            name = GLD_ID(id);
        } else {
            name = GLD_Name(soln.get("?name").toString(), false);
        }
        res = model.getResource(id);
        String len = soln.get("?len").toString();
        phs = WirePhases(model, res, ptPhsLine1, ptPhsLine2);
        bus1 = GetBusName(model, id, 1);
        bus2 = GetBusName(model, id, 2);
        double dLen = 3.28084 * SafeDouble(res, ptLineLen, 1.0);

        GldNode nd1 = mapNodes.get(bus1);
        nd1.nomvln = FindBaseVoltage(res, ptEquip, ptEqBaseV, ptLevBaseV, ptBaseNomV) / Math.sqrt(3.0);
        GldNode nd2 = mapNodes.get(bus2);
        nd2.nomvln = nd1.nomvln;

        if (phs.contains("S")) { // look for the primary phase at either end of this triplex line segment
            if (nd1.phases.length() > 0)
                phs = nd1.phases + phs;
            if (nd2.phases.length() > 0)
                phs = nd2.phases + phs;
        }
        nd1.AddPhases(phs);
        nd2.AddPhases(phs);

        String zPhase = SafeResourceLookup(model, ptName, res, ptPhsZ, "");
        String zParms = GetACLineParameters(model, name, res, dLen, freq, phs, out);
        String zSpace = GetLineSpacing(model, res);
        String linecode = "";

        if (nd1.bSecondary) {
            if (bWantSec) {
                out.println("object triplex_line {\n   name \"tpx_" + name + "\";");
                out.println("   phases " + phs + ";");
                if (nd1.HasLoad()) {
                    out.println("  from \"" + bus2 + "\";");
                    out.println("   to \"" + bus1 + "\";");
                } else {
                    out.println("  from \"" + bus1 + "\";");
                    out.println("   to \"" + bus2 + "\";");
                }
                out.println("   length " + String.format("%6g", dLen) + ";");
                if (zPhase.length() > 0) {
                    out.println("  configuration \"tcon_" + zPhase + "\";");
                } else if (zParms.length() > 0) {
                    out.println("  configuration \"" + zParms + "\";");
                }
                out.println("}");
            }
        } else {
            out.println("object overhead_line {\n  name \"line_" + name + "\";");
            out.println("   phases " + phs + ";");
            out.println("   from \"" + bus1 + "\";");
            out.println("   to \"" + bus2 + "\";");
            out.println("   length " + String.format("%6g", dLen) + ";");
            if (zPhase.length() > 0) {
                out.println("  configuration \"lcon_" + zPhase + "_" + phs + "\";");
            } else if (zParms.length() > 0) {
                out.println("  configuration \"" + zParms + "\";");
            }
            out.println("}");
        }

        //         String zAmps = "";
        //         if (zParms.length () > 0) {
        //            zAmps = FindConductorAmps (model, res, ptDataSheet, ptAmps);
        //            out.println (zAmps);
        //         }
    }

    // LoadBreakSwitch ==> Line switch=y
    query = QueryFactory.create(qPrefix + "select ?s ?name ?open where {?s r:type c:LoadBreakSwitch. "
            + "?s c:IdentifiedObject.name ?name;" + "    c:Switch.normalOpen ?open" + "}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    Property ptPhsSwt1 = model.getProperty(nsCIM, "SwitchPhase.Switch");
    Property ptPhsSwt2 = model.getProperty(nsCIM, "SwitchPhase.phaseSide1"); // TODO - phaseSide2?
    while (results.hasNext()) {
        soln = results.next();

        id = soln.get("?s").toString();
        name = GLD_Name(soln.get("?name").toString(), false);
        res = model.getResource(id);
        phs = WirePhases(model, res, ptPhsSwt1, ptPhsSwt2);
        String open = soln.get("?open").toString();

        bus1 = GetBusName(model, id, 1);
        bus2 = GetBusName(model, id, 2);

        GldNode nd1 = mapNodes.get(bus1);
        nd1.nomvln = FindBaseVoltage(res, ptEquip, ptEqBaseV, ptLevBaseV, ptBaseNomV) / Math.sqrt(3.0);
        nd1.AddPhases(phs);
        GldNode nd2 = mapNodes.get(bus2);
        nd2.nomvln = nd1.nomvln;
        nd2.AddPhases(phs);

        out.println("object switch {\n  name \"swt_" + name + "\";");
        out.println("   phases " + phs + ";");
        out.println("   from \"" + bus1 + "\";");
        out.println("   to \"" + bus2 + "\";");
        if (open.equals("false")) {
            out.println("   status CLOSED;");
        } else {
            out.println("   status OPEN;");
        }
        out.println("}");
    }

    // Fuse ==> Line switch=y
    query = QueryFactory.create(qPrefix + "select ?s ?name ?open where {?s r:type c:Fuse. "
            + "?s c:IdentifiedObject.name ?name;" + "    c:Switch.normalOpen ?open" + "}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    if (results.hasNext()) {
        out.println();
        out.println("// Fuses");
    }
    while (results.hasNext()) {
        soln = results.next();

        id = soln.get("?s").toString();
        name = GLD_Name(soln.get("?name").toString(), false);
        res = model.getResource(id);
        phs = WirePhases(model, res, ptPhsSwt1, ptPhsSwt2);
        String open = soln.get("?open").toString();

        bus1 = GetBusName(model, id, 1);
        bus2 = GetBusName(model, id, 2);

        GldNode nd1 = mapNodes.get(bus1);
        nd1.nomvln = FindBaseVoltage(res, ptEquip, ptEqBaseV, ptLevBaseV, ptBaseNomV) / Math.sqrt(3.0);
        nd1.AddPhases(phs);
        GldNode nd2 = mapNodes.get(bus2);
        nd2.nomvln = nd1.nomvln;
        nd2.AddPhases(phs);

        //         out.println ("new Line." + name + " phases=" + Integer.toString(phs_cnt) + " bus1=" + bus1 + " bus2=" + bus2 
        //                                       + " switch=y // CIM Fuse");
        if (open.equals("false")) {
            //            out.println ("   close Line." + name + " 1");
        } else {
            //            out.println ("   open Line." + name + " 1");
        }
    }

    // Breaker ==> Line switch=y   (NOTE: a source may be attached to the first instance)
    query = QueryFactory.create(
            qPrefix + "select ?s ?name where {?s r:type c:Breaker. " + "?s c:IdentifiedObject.name ?name}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    if (results.hasNext()) {
        out.println();
        out.println("// Breakers");
    }
    while (results.hasNext()) {
        soln = results.next();

        id = soln.get("?s").toString();
        name = GLD_Name(soln.get("?name").toString(), false);
        res = model.getResource(id);
        phs = WirePhases(model, res, ptPhsSwt1, ptPhsSwt2);
        String open = SafeProperty(res, ptOpen, "false");

        bus1 = GetBusName(model, id, 1);
        bus2 = GetBusName(model, id, 2);

        GldNode nd1 = mapNodes.get(bus1);
        nd1.nomvln = FindBaseVoltage(res, ptEquip, ptEqBaseV, ptLevBaseV, ptBaseNomV) / Math.sqrt(3.0);
        nd1.AddPhases(phs);
        GldNode nd2 = mapNodes.get(bus2);
        nd2.nomvln = nd1.nomvln;
        nd2.AddPhases(phs);

        //         out.println ("new Line." + name + " phases=" + Integer.toString(phs_cnt) + " bus1=" + bus1 + " bus2=" + bus2 
        //                                       + " switch=y // CIM Breaker");
        if (open.equals("false")) {
            //            out.println ("   close Line." + name + " 1");
        } else {
            //            out.println ("   open Line." + name + " 1");
        }
    }

    // Disconnector ==> Line switch=y
    query = QueryFactory.create(qPrefix + "select ?s ?name where {?s r:type c:Disconnector. "
            + "?s c:IdentifiedObject.name ?name}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    if (results.hasNext()) {
        out.println();
        out.println("// Disconnectors");
    }
    while (results.hasNext()) {
        soln = results.next();

        id = soln.get("?s").toString();
        name = GLD_Name(soln.get("?name").toString(), false);
        res = model.getResource(id);
        phs = WirePhases(model, res, ptPhsSwt1, ptPhsSwt2);
        String open = SafeProperty(res, ptOpen, "false");

        bus1 = GetBusName(model, id, 1);
        bus2 = GetBusName(model, id, 2);

        GldNode nd1 = mapNodes.get(bus1);
        nd1.nomvln = FindBaseVoltage(res, ptEquip, ptEqBaseV, ptLevBaseV, ptBaseNomV) / Math.sqrt(3.0);
        nd1.AddPhases(phs);
        GldNode nd2 = mapNodes.get(bus2);
        nd2.nomvln = nd1.nomvln;
        nd2.AddPhases(phs);

        //         out.println ("new Line." + name + " phases=" + Integer.toString(phs_cnt) + " bus1=" + bus1 + " bus2=" + bus2 
        //                                       + " switch=y // CIM Disconnector");
        if (open.equals("false")) {
            //            out.println ("   close Line." + name + " 1");
        } else {
            //            out.println ("   open Line." + name + " 1");
        }
    }

    // unsupported stuff - TODO - add Jumper and Disconnector
    out.println();
    query = QueryFactory.create(qPrefix + "select ?s where {?s r:type c:Junction}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    while (results.hasNext()) {
        soln = results.next();
        id = soln.get("?s").toString();
        res = model.getResource(id);
        name = SafeResName(res, ptName);
        //         out.println ("// new Junction." + name);
    }
    query = QueryFactory.create(qPrefix + "select ?s where {?s r:type c:BusbarSection}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    while (results.hasNext()) {
        soln = results.next();
        id = soln.get("?s").toString();
        res = model.getResource(id);
        name = SafeResName(res, ptName);
        //         out.println ("// new BusbarSection." + name);
    }
    query = QueryFactory.create(qPrefix + "select ?s where {?s r:type c:Bay}");
    qexec = QueryExecutionFactory.create(query, model);
    results = qexec.execSelect();
    while (results.hasNext()) {
        soln = results.next();
        id = soln.get("?s").toString();
        res = model.getResource(id);
        name = SafeResName(res, ptName);
        //         out.println ("// new Bay." + name);
    }

    // write the swing node as a substation, and exclude from the others
    for (HashMap.Entry<String, GldNode> pair : mapNodes.entrySet()) {
        GldNode nd = pair.getValue();
        if (nd.bSwing) {
            out.println("object substation {");
            out.println("  name \"" + nd.name + "\";");
            out.println("  bustype SWING;");
            out.println("  phases " + nd.GetPhases() + ";");
            out.println("  nominal_voltage " + String.format("%6g", nd.nomvln) + ";");
            out.println("  base_power 12MVA;");
            out.println("  power_convergence_value 100VA;");
            out.println("  positive_sequence_voltage ${VSOURCE};");
            out.println("}");
            break; // there can be only one swing bus
        }
    }

    // write the nodes and loads; by now, all should have phases and nominal voltage
    for (HashMap.Entry<String, GldNode> pair : mapNodes.entrySet()) {
        GldNode nd = pair.getValue();
        if (nd.HasLoad() && !nd.bSwing) {
            nd.RescaleLoad(load_scale);
            if (bWantZIP) {
                nd.ApplyZIP(Zcoeff, Icoeff, Pcoeff);
            }
            Complex va = new Complex(nd.nomvln);
            Complex vb = va.multiply(neg120);
            Complex vc = va.multiply(pos120);
            Complex amps;
            Complex vmagsq = new Complex(nd.nomvln * nd.nomvln);
            if (nd.bSecondary) {
                if (bWantSec) {
                    out.println("object triplex_load {");
                    out.println("    name \"" + nd.name + "\";");
                    out.println("    phases " + nd.GetPhases() + ";");
                    out.println("    nominal_voltage " + String.format("%6g", nd.nomvln) + ";");
                    Complex base1 = new Complex(nd.pa_z + nd.pa_i + nd.pa_p, nd.qa_z + nd.qa_i + nd.qa_p);
                    Complex base2 = new Complex(nd.pb_z + nd.pb_i + nd.pb_p, nd.qb_z + nd.qb_i + nd.qb_p);
                    if (bWantSched) {
                        out.println("    base_power_1 " + fSched + ".value*" + String.format("%6g", base1.abs())
                                + ";");
                        out.println("    base_power_2 " + fSched + ".value*" + String.format("%6g", base2.abs())
                                + ";");
                    } else {
                        out.println("    base_power_1 " + String.format("%6g", base1.abs()) + ";");
                        out.println("    base_power_2 " + String.format("%6g", base2.abs()) + ";");
                    }
                    if (nd.pa_p > 0.0) {
                        Complex base = new Complex(nd.pa_p, nd.qa_p);
                        out.println("  power_pf_1 " + String.format("%6g", nd.pa_p / base.abs()) + ";");
                        out.println(
                                "  power_fraction_1 " + String.format("%6g", nd.pa_p / base1.getReal()) + ";");
                    }
                    if (nd.pb_p > 0.0) {
                        Complex base = new Complex(nd.pb_p, nd.qb_p);
                        out.println("  power_pf_2 " + String.format("%6g", nd.pb_p / base.abs()) + ";");
                        out.println(
                                "  power_fraction_2 " + String.format("%6g", nd.pb_p / base2.getReal()) + ";");
                    }
                    if (nd.pa_i > 0.0) {
                        Complex base = new Complex(nd.pa_i, nd.qa_i);
                        out.println("  current_pf_1 " + String.format("%6g", nd.pa_i / base.abs()) + ";");
                        out.println("  current_fraction_1 " + String.format("%6g", nd.pa_i / base1.getReal())
                                + ";");
                    }
                    if (nd.pb_i > 0.0) {
                        Complex base = new Complex(nd.pb_i, nd.qb_i);
                        out.println("  current_pf_2 " + String.format("%6g", nd.pb_i / base.abs()) + ";");
                        out.println("  current_fraction_2 " + String.format("%6g", nd.pb_i / base2.getReal())
                                + ";");
                    }
                    if (nd.pa_z > 0.0) {
                        Complex base = new Complex(nd.pa_z, nd.qa_z);
                        out.println("  impedance_pf_1 " + String.format("%6g", nd.pa_z / base.abs()) + ";");
                        out.println("  impedance_fraction_1 " + String.format("%6g", nd.pa_z / base1.getReal())
                                + ";");
                    }
                    if (nd.pb_z > 0.0) {
                        Complex base = new Complex(nd.pb_z, nd.qb_z);
                        out.println("  impedance_pf_2 " + String.format("%6g", nd.pb_z / base.abs()) + ";");
                        out.println("  impedance_fraction_2 " + String.format("%6g", nd.pb_z / base2.getReal())
                                + ";");
                    }
                    out.println("}");
                }
            } else {
                if (bWantSched) { // TODO
                } else {
                    out.println("object load {");
                    out.println("    name \"" + nd.name + "\";");
                    out.println("    phases " + nd.GetPhases() + ";");
                    out.println("    nominal_voltage " + String.format("%6g", nd.nomvln) + ";");
                    if (nd.pa_p > 0.0 || nd.qa_p != 0.0) {
                        out.println("    constant_power_A " + CFormat(new Complex(nd.pa_p, nd.qa_p)) + ";");
                    }
                    if (nd.pb_p > 0.0 || nd.qb_p != 0.0) {
                        out.println("    constant_power_B " + CFormat(new Complex(nd.pb_p, nd.qb_p)) + ";");
                    }
                    if (nd.pc_p > 0.0 || nd.qc_p != 0.0) {
                        out.println("    constant_power_C " + CFormat(new Complex(nd.pc_p, nd.qc_p)) + ";");
                    }
                    if (nd.pa_z > 0.0 || nd.qa_z != 0.0) {
                        Complex s = new Complex(nd.pa_z, nd.qa_z);
                        Complex z = vmagsq.divide(s.conjugate());
                        out.println("    constant_impedance_A " + CFormat(z) + ";");
                    }
                    if (nd.pb_z > 0.0 || nd.qb_z != 0.0) {
                        Complex s = new Complex(nd.pb_z, nd.qb_z);
                        Complex z = vmagsq.divide(s.conjugate());
                        out.println("    constant_impedance_B " + CFormat(z) + ";");
                    }
                    if (nd.pc_z > 0.0 || nd.qc_z != 0.0) {
                        Complex s = new Complex(nd.pc_z, nd.qc_z);
                        Complex z = vmagsq.divide(s.conjugate());
                        out.println("    constant_impedance_C " + CFormat(z) + ";");
                    }
                    if (nd.pa_i > 0.0 || nd.qa_i != 0.0) {
                        Complex s = new Complex(nd.pa_i, nd.qa_i);
                        amps = s.divide(va).conjugate();
                        out.println("    constant_current_A " + CFormat(amps) + ";");
                    }
                    if (nd.pb_i > 0.0 || nd.qb_i != 0.0) {
                        Complex s = new Complex(nd.pb_i, nd.qb_i);
                        amps = s.divide(va.multiply(neg120)).conjugate();
                        out.println("    constant_current_B " + CFormat(amps) + ";");
                    }
                    if (nd.pc_i > 0.0 || nd.qc_i != 0.0) {
                        Complex s = new Complex(nd.pc_i, nd.qc_i);
                        amps = s.divide(va.multiply(pos120)).conjugate();
                        out.println("    constant_current_C " + CFormat(amps) + ";");
                    }
                    out.println("}");
                }
            }
        } else if (!nd.bSwing) {
            if (nd.bSecondary) {
                if (bWantSec) {
                    out.println("object triplex_node {");
                    out.println("    name \"" + nd.name + "\";");
                    out.println("    phases " + nd.GetPhases() + ";");
                    out.println("    nominal_voltage " + String.format("%6g", nd.nomvln) + ";");
                    out.println("}");
                }
            } else {
                out.println("object node {");
                out.println("    name \"" + nd.name + "\";");
                out.println("    phases " + nd.GetPhases() + ";");
                out.println("    nominal_voltage " + String.format("%6g", nd.nomvln) + ";");
                out.println("}");
            }
        }
    }
    out.println();
    out.println("// total load = " + String.format("%6g", total_load_w) + " W");

    out.println("// buscoords " + fBus);
    out.close();

    //      for (HashMap.Entry<String,SpacingCount> pair : mapSpacings.entrySet()) {
    //         System.out.printf ("%s ==> %d, %d\n", pair.getKey(), pair.getValue().getNumConductors(), pair.getValue().getNumPhases());
    //      }
}

From source file:org.briljantframework.example.array.Perf.java

private static int mandel(double re, double im) {
    int n = 0;/*from www .jav  a 2  s .  co m*/
    Complex z = new Complex(re, im);
    Complex c = new Complex(re, im);
    for (n = 0; n <= 79; ++n) {
        if (z.abs() > 2.0) {
            n -= 1;
            break;
        }

        // z = z*z + c
        z = z.multiply(z).add(c);
    }
    return n + 1;
}