Example usage for java.lang Math acos

List of usage examples for java.lang Math acos

Introduction

In this page you can find the example usage for java.lang Math acos.

Prototype

public static double acos(double a) 

Source Link

Document

Returns the arc cosine of a value; the returned angle is in the range 0.0 through pi.

Usage

From source file:org.opensha.commons.geo.LocationUtils.java

/**
 * Computes the shortest distance between a point and a line segment (i.e.
 * great-circle segment). Both the line and point are assumed to be at the
 * earth's surface; the depth component of each <code>Location</code> is
 * ignored. This method uses the true spherical geometric function for
 * 'off-track distance'; See <a//  ww  w  . j  ava2  s.c  o  m
 * href="http://williams.best.vwh.net/avform.htm#XTE"> Aviation
 * Formulary</a> for source. This method always returns a positive result.<br/>
 * <br/>
 * This method, though more accurate over longer distances and line lengths,
 * is up to 20x slower than
 * {@link #distanceToLineSegmentFast(Location, Location, Location)}. However,
 * this method returns accurate results for values spanning #177;180&#176;. <br/>
 * <br/>
 * If the line should instead be treated as infinite, use
 * {@link #distanceToLine(Location, Location, Location)} instead.
 * 
 * @param p1 the first <code>Location</code> point on the line
 * @param p2 the second <code>Location</code> point on the line
 * @param p3 the <code>Location</code> point for which distance will be
 *        calculated
 * @return the shortest distance in km between the supplied point and line
 * @see #distanceToLineFast(Location, Location, Location)
 * @see #distanceToLine(Location, Location, Location)
 */
public static double distanceToLineSegment(Location p1, Location p2, Location p3) {

    // repeat calcs in distanceToLine() to cut down on replication of
    // expensive trig ops that would result from calling distanceToLine()

    // angular distance
    double ad13 = angle(p1, p3);
    // delta azimuth p1 to p3 and azimuth p1 to p2
    double Daz13az12 = azimuthRad(p1, p3) - azimuthRad(p1, p2);
    // cross-track distance (in radians)
    double xtd = Math.asin(Math.sin(ad13) * Math.sin(Daz13az12));
    // along-track distance (in km)
    double atd = Math.acos(Math.cos(ad13) / Math.cos(xtd)) * EARTH_RADIUS_MEAN;
    // check if beyond p3
    if (atd > horzDistance(p1, p2))
        return horzDistance(p2, p3);
    // check if before p1
    if (Math.cos(Daz13az12) < 0)
        return horzDistance(p1, p3);
    return (Math.abs(xtd) < TOLERANCE) ? 0.0 : Math.abs(xtd) * EARTH_RADIUS_MEAN;
}

From source file:uk.ac.diamond.scisoft.xpdf.views.XPDFPhase.java

/**
 * Changes the present unit cell from hexagonal to rhombohedral.
 * <p> /*from   w  w w  . ja va 2s .  c o  m*/
 * Changes the unit cell parameters from a hexagonal basis
 * (aac 90,90,120)to a rhombohedral basis (aaa, ), and sets the space
 * group to the rhombohedral equivalent.
 */
private void unitCelltoRhombohedral() {
    setSpaceGroup(spaceGroup.asRhombohedral());

    double ah = unitCellLengths[0], c = unitCellLengths[2];
    // Convert them to the squared lengths
    ah *= ah;
    c *= c;
    // Squared rhombohedral unit cell edge length 
    double ar = ah / 3 + c / 9;
    double alpha = Math.toDegrees(Math.acos((-ah / 6 + c / 9) / ar));
    // Make ar the length
    ar = Math.sqrt(ar);
    unitCellLengths[0] = unitCellLengths[1] = unitCellLengths[2] = ar;
    unitCellDegrees[0] = unitCellDegrees[1] = unitCellDegrees[2] = alpha;
}

From source file:matteroverdrive.util.RenderUtils.java

public static void beginDrawinngBlockScreen(double x, double y, double z, ForgeDirection side, Color color,
        TileEntity entity, double offset, float glowAlpha) {
    glEnable(GL_BLEND);//w w w .jav a 2s .  c  om
    glDisable(GL_LIGHTING);
    disableLightmap();

    Vector3f dir = new Vector3f(side.offsetX, side.offsetY, side.offsetZ);
    Vector3f front = new Vector3f(0, 0, -1);
    Vector3f c = Vector3f.cross(front, dir, null);
    double omega = Math.acos(Vector3f.dot(front, dir));
    if (omega == Math.PI) {
        c.y = 1;
    }

    glPushMatrix();
    glTranslated(dir.x * (0.5 + offset), dir.y * (0.5 + offset), dir.z * (0.5 + offset));
    glTranslated(x + 0.5, y + 0.5, z + 0.5);
    glRotated(omega * (180 / Math.PI), c.x, c.y, c.z);
    glRotated(180, 0, 0, 1);
    glTranslated(-0.5, -0.5, 0);

    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR);

    double multiply = (MOMathHelper.noise(entity.xCoord, entity.getWorldObj().getWorldTime() * 0.01,
            entity.zCoord) * 0.5 + 0.5) * glowAlpha;
    glColor3d(color.getFloatR() * multiply, color.getFloatG() * multiply, color.getFloatB() * multiply);
    Minecraft.getMinecraft().getTextureManager()
            .bindTexture(TileEntityRendererPatternMonitor.screenTextureGlow);
    RenderUtils.drawPlane(1);

    glTranslated(0, 0, -0.05);
    glColor3d(color.getFloatR() * 0.05f, color.getFloatG() * 0.05f, color.getFloatB() * 0.05f);
    Minecraft.getMinecraft().getTextureManager()
            .bindTexture(TileEntityRendererPatternMonitor.screenTextureBack);
    RenderUtils.drawPlane(1);
}

From source file:sphericalGeo.SphericalDiffusionModel.java

public static double getAngle(double[] start, double[] stop) {
    double latitude1 = start[0];
    double longitude1 = start[1];
    double theta1 = (latitude1) * Math.PI / 180.0;
    if (longitude1 < 0)
        longitude1 += 360;/*  w w  w.ja  va 2s.co m*/
    double phi1 = longitude1 * Math.PI / 180;

    double latitude2 = stop[0];
    double longitude2 = stop[1];
    double theta2 = (latitude2) * Math.PI / 180.0;
    if (longitude2 < 0)
        longitude2 += 360;
    double phi2 = longitude2 * Math.PI / 180;

    double Deltalambda = phi2 - phi1;

    // See http://en.wikipedia.org/wiki/Great-circle_distance#Formulas
    double angle = Math.acos(
            Math.sin(theta1) * Math.sin(theta2) + Math.cos(theta1) * Math.cos(theta2) * Math.cos(Deltalambda));
    return angle;
}

From source file:be.makercafe.apps.makerbench.editors.GCodeEditor.java

/**
 * Draws a line in 3D between 2 3D points on the given group.
 * /* ww  w  . j  a  va 2 s .  c  om*/
 * @param origin
 *            Origin point
 * @param target
 *            Target point
 * @return 3D line (cylinder) between to points
 */
private Cylinder drawLine3D(Group group, Point3D origin, Point3D target, Material color) {
    if (color == null) {
        color = MATERIAL_BLACK; // default to orange
    }
    Point3D yAxis = new Point3D(0, 1, 0);
    Point3D diff = target.subtract(origin);
    double height = diff.magnitude();

    Point3D mid = target.midpoint(origin);
    Translate moveToMidpoint = new Translate(mid.getX(), mid.getY(), mid.getZ());

    Point3D axisOfRotation = diff.crossProduct(yAxis);
    double angle = Math.acos(diff.normalize().dotProduct(yAxis));
    Rotate rotateAroundCenter = new Rotate(-Math.toDegrees(angle), axisOfRotation);

    Cylinder line = new Cylinder(1, height);
    line.setMaterial(color);

    line.getTransforms().addAll(moveToMidpoint, rotateAroundCenter);

    if (group != null) {
        group.getChildren().add(line);
    }

    return line;
}

From source file:com.liferay.events.global.mobile.Utils.java

public static double getDistanceBetween(double lat1, double lon1, double lat2, double lon2) {
    if (lat1 == lat2 && lon1 == lon2) {
        return 0;
    }/*from w w w  . j a va 2 s .  c  om*/
    double theta = lon1 - lon2;
    double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2))
            + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
    if (dist == 0) {
        return 0;
    }
    dist = Math.acos(dist);
    dist = rad2deg(dist);
    return (dist * 60 * 1.1515 * 1.609344);
}

From source file:util.Utils.java

/**
 * ???//from   w ww .  j a v  a2s.c om
 *
 * @param lat_a
 * @param lng_a
 * @param lat_b
 * @param lng_b
 * @return
 */
public static double getDistance(double lat_a, double lng_a, double lat_b, double lng_b) {
    double pk = 180 / 3.14169d;
    double a1 = lat_a / pk;
    double a2 = lng_a / pk;
    double b1 = lat_b / pk;
    double b2 = lng_b / pk;
    double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
    double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
    double t3 = Math.sin(a1) * Math.sin(b1);
    double tt = Math.acos(t1 + t2 + t3);
    return 6366000 * tt;
}

From source file:Rotation.java

/** Get the angle of the rotation.
 * @return angle of the rotation (between 0 and &pi;)
 *//*w ww  .j  a  v a 2 s. com*/
public double getAngle() {
    if ((q0 < -0.1) || (q0 > 0.1)) {
        return 2 * Math.asin(Math.sqrt(q1 * q1 + q2 * q2 + q3 * q3));
    } else if (q0 < 0) {
        return 2 * Math.acos(-q0);
    }
    return 2 * Math.acos(q0);
}

From source file:util.Utils.java

/**
 * ???/*from w ww .  j av  a 2 s.c o  m*/
 *
 * @param lat_a
 * @param lng_a
 * @param lat_b
 * @param lng_b
 * @return
 */
public static String getDistance1(double lat_a, double lng_a, double lat_b, double lng_b) {
    double pk = 180 / 3.14169d;
    double a1 = lat_a / pk;
    double a2 = lng_a / pk;
    double b1 = lat_b / pk;
    double b2 = lng_b / pk;
    double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
    double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
    double t3 = Math.sin(a1) * Math.sin(b1);
    double tt = Math.acos(t1 + t2 + t3);
    int v = (int) (6366000 * tt);
    int km = v / 1000;

    StringBuilder sb = new StringBuilder();
    if (km > 0) {
        int m = v % 1000 / 100;
        Log.d(TAG, "m:" + m);
        sb.append(km + "." + m + "km");
    } else {
        sb.append(v + "m");
    }

    return sb.toString();
}

From source file:com.mbientlab.metawear.tutorial.starter.DeviceSetupActivityFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // Grab Date/*  ww  w  . ja  v a2 s .  c o  m*/
    year = Calendar.getInstance().get(Calendar.YEAR);
    month = Calendar.getInstance().get(Calendar.MONTH) + 1;
    day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);

    // Initialize variables used for trial name
    SubjectCode = (EditText) view.findViewById(R.id.SubjectCode);
    TrialNumber = (EditText) view.findViewById(R.id.TrialNumber);
    TrialType = (EditText) view.findViewById(R.id.TrialType);
    FileName_text = (TextView) view.findViewById(R.id.FileName_text);

    // Initialize buttons for device behavior
    ProgramState_text = (TextView) view.findViewById(R.id.ProgramState_text);
    ProgramState_switch = (Switch) view.findViewById(R.id.ProgramState);

    // Initialize thresholds and feedback toggles
    Threshold_L = (EditText) view.findViewById(R.id.Threshold_L);
    MotorToggle_switch = (Switch) view.findViewById(R.id.MotorToggle_switch);

    Threshold_L.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Threshold_L_string = Threshold_L.getText().toString();
            if (Threshold_L_string.length() > 0) {
                threshold_L = Double.parseDouble(Threshold_L_string);
            } else {

            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });
    SubjectCode.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            SubjectCode_string = SubjectCode.getText().toString();
            FileName_text.setText("" + year + "" + month + "" + day + "_" + SubjectCode_string + "_"
                    + TrialType_string + "_" + TrialNumber_string_final);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    TrialType.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            TrialType_string = TrialType.getText().toString();
            FileName_text.setText("" + year + "" + month + "" + day + "_" + SubjectCode_string + "_"
                    + TrialType_string + "_" + TrialNumber_string_final);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    TrialNumber.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            TrialNumber_string = TrialNumber.getText().toString();
            if (TrialNumber_string.length() > 0) {
                TrialNumber_int = Integer.parseInt(TrialNumber_string);
                TrialNumber_string_final = String.format("%03d", TrialNumber_int);
            } else {
            }

            /*if (TrialNumber_string.length() == 1){
            TrialNumber_string_final = "00"+TrialNumber_string;
            }
            if (TrialNumber_string.length() == 2){
            TrialNumber_string_final = "0"+TrialNumber_string;
            }
            if (TrialNumber_string.length() == 3){
            TrialNumber_string_final = TrialNumber_string;
            }*/
            FileName_text.setText("" + year + "" + month + "" + day + "_" + SubjectCode_string + "_"
                    + TrialType_string + "_" + TrialNumber_string_final);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

    MotorToggle_switch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (MotorToggle_state == false) {
                MotorToggle_state = true;
            } else {
                MotorToggle_state = false;
            }
        }
    });

    ProgramState_switch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (ProgramState_status == false) {
                ProgramState_status = true;
                accelerometer.acceleration().addRouteAsync(new RouteBuilder() {
                    @Override
                    public void configure(RouteComponent source) {
                        source.stream(new Subscriber() {
                            @Override
                            public void apply(Data data, Object... env) {

                                // Read Accel and Prepare for writing to CSV
                                accel_raw_x = data.value(Acceleration.class).x();
                                accel_raw_y = data.value(Acceleration.class).y();
                                accel_raw_z = data.value(Acceleration.class).z();
                                accel_string_x = Double.toString(accel_raw_x);
                                accel_string_y = Double.toString(accel_raw_y);
                                accel_string_z = Double.toString(accel_raw_z);

                                if (initial_accel_loop == 1) {
                                    double vertical_sensor_norm_init = Math.sqrt(accel_raw_x * accel_raw_x
                                            + accel_raw_y * accel_raw_y + accel_raw_z * accel_raw_z);
                                    vertical_sensor_0 = accel_raw_x * 1 / vertical_sensor_norm_init;
                                    vertical_sensor_1 = accel_raw_y * 1 / vertical_sensor_norm_init;
                                    vertical_sensor_2 = accel_raw_z * 1 / vertical_sensor_norm_init;

                                    initial_accel_loop = 0;
                                }
                            }
                        });
                    }
                }).continueWith(new Continuation<Route, Void>() {

                    @Override
                    public Void then(Task<Route> task) throws Exception {
                        accelerometer.acceleration().start();
                        accelerometer.start();
                        Log.i("MainActivity", "Running!");

                        initial_accel_loop = 1;

                        ProgramState_text.setText("Collecting");
                        return null;
                    }
                });
                gyroscope.angularVelocity().addRouteAsync(new RouteBuilder() {
                    @Override
                    public void configure(RouteComponent source) {
                        source.stream(new Subscriber() {
                            @Override
                            public void apply(Data data, Object... env) {

                                // Read Gyro and Prepare for writing to CSV
                                gyro_raw_x = data.value(AngularVelocity.class).x();
                                gyro_raw_y = data.value(AngularVelocity.class).y();
                                gyro_raw_z = data.value(AngularVelocity.class).z();
                                gyro_raw_x = Math.toRadians(gyro_raw_x);
                                gyro_raw_y = Math.toRadians(gyro_raw_y);
                                gyro_raw_z = Math.toRadians(gyro_raw_z);

                                gyro_string_x = Double.toString(gyro_raw_x);
                                gyro_string_y = Double.toString(gyro_raw_y);
                                gyro_string_z = Double.toString(gyro_raw_z);

                                if (initial_accel_loop == 0) {
                                    // Get Timestamp
                                    currentTime = System.currentTimeMillis();
                                    deltaTime = (currentTime - previousTime) / 1000;

                                    if (gyro_raw_x != previous_gyro_raw_x) {
                                        previous_gyro_raw_x = gyro_raw_x;

                                        totalTime = totalTime + deltaTime;
                                        time_stamp = Double.toString(totalTime);
                                        previousTime = currentTime;

                                        //// CALCULATE INCLINATION ANGLE /////
                                        vertical_sensor_from_accel_0 = accel_raw_x;
                                        vertical_sensor_from_accel_1 = accel_raw_y;
                                        vertical_sensor_from_accel_2 = accel_raw_z;

                                        // normalize accelerometer estimate
                                        vertical_sensor_from_accel_norm = Math.sqrt(
                                                vertical_sensor_from_accel_0 * vertical_sensor_from_accel_0
                                                        + vertical_sensor_from_accel_1
                                                                * vertical_sensor_from_accel_1
                                                        + vertical_sensor_from_accel_2
                                                                * vertical_sensor_from_accel_2);

                                        vertical_sensor_from_accel_0 = vertical_sensor_from_accel_0
                                                / vertical_sensor_from_accel_norm;
                                        vertical_sensor_from_accel_1 = vertical_sensor_from_accel_1
                                                / vertical_sensor_from_accel_norm;
                                        vertical_sensor_from_accel_2 = vertical_sensor_from_accel_2
                                                / vertical_sensor_from_accel_norm;

                                        // GYROSCOPE INCLINATION ANGLE
                                        angular_velocity_body_matrix_0_0 = 0;
                                        angular_velocity_body_matrix_0_1 = -gyro_raw_z;
                                        angular_velocity_body_matrix_0_2 = gyro_raw_y;
                                        angular_velocity_body_matrix_1_0 = gyro_raw_z;
                                        angular_velocity_body_matrix_1_1 = 0;
                                        angular_velocity_body_matrix_1_2 = -gyro_raw_x;
                                        angular_velocity_body_matrix_2_0 = -gyro_raw_y;
                                        angular_velocity_body_matrix_2_1 = gyro_raw_x;
                                        angular_velocity_body_matrix_2_2 = 0;

                                        // rotational velocity based on gyroscope readings
                                        vertical_sensor_dot_from_gyro_0 = -(angular_velocity_body_matrix_0_0
                                                * vertical_sensor_0
                                                + angular_velocity_body_matrix_0_1 * vertical_sensor_1
                                                + angular_velocity_body_matrix_0_2 * vertical_sensor_2);
                                        vertical_sensor_dot_from_gyro_1 = -(angular_velocity_body_matrix_1_0
                                                * vertical_sensor_0
                                                + angular_velocity_body_matrix_1_1 * vertical_sensor_1
                                                + angular_velocity_body_matrix_1_2 * vertical_sensor_2);
                                        vertical_sensor_dot_from_gyro_2 = -(angular_velocity_body_matrix_2_0
                                                * vertical_sensor_0
                                                + angular_velocity_body_matrix_2_1 * vertical_sensor_1
                                                + angular_velocity_body_matrix_2_2 * vertical_sensor_2);

                                        // rotational velocity based on difference to accelerometer estimate
                                        vertical_sensor_dot_from_accel_0 = -alpha
                                                * (vertical_sensor_0 - vertical_sensor_from_accel_0);
                                        vertical_sensor_dot_from_accel_1 = -alpha
                                                * (vertical_sensor_1 - vertical_sensor_from_accel_1);
                                        vertical_sensor_dot_from_accel_2 = -alpha
                                                * (vertical_sensor_2 - vertical_sensor_from_accel_2);

                                        // combine the two estimates
                                        vertical_sensor_dot_0 = vertical_sensor_dot_from_gyro_0
                                                + vertical_sensor_dot_from_accel_0;
                                        vertical_sensor_dot_1 = vertical_sensor_dot_from_gyro_1
                                                + vertical_sensor_dot_from_accel_1;
                                        vertical_sensor_dot_2 = vertical_sensor_dot_from_gyro_2
                                                + vertical_sensor_dot_from_accel_2;

                                        // integrate rotational velocity
                                        vertical_sensor_0 = vertical_sensor_0
                                                + deltaTime * vertical_sensor_dot_0;
                                        vertical_sensor_1 = vertical_sensor_1
                                                + deltaTime * vertical_sensor_dot_1;
                                        vertical_sensor_2 = vertical_sensor_2
                                                + deltaTime * vertical_sensor_dot_2;

                                        // normalize after integration
                                        vertical_sensor_norm = Math.sqrt(vertical_sensor_0 * vertical_sensor_0
                                                + vertical_sensor_1 * vertical_sensor_1
                                                + vertical_sensor_2 * vertical_sensor_2);
                                        vertical_sensor_0 = vertical_sensor_0 / vertical_sensor_norm;
                                        vertical_sensor_1 = vertical_sensor_1 / vertical_sensor_norm;
                                        vertical_sensor_2 = vertical_sensor_2 / vertical_sensor_norm;

                                        // calculate inclination angles
                                        inclination_angle = Math.acos(vertical_sensor_0 * sensor_axis_sensor_0
                                                + vertical_sensor_1 * sensor_axis_sensor_1
                                                + vertical_sensor_2 * sensor_axis_sensor_2);
                                        inclination_angle_from_accel = Math
                                                .acos(vertical_sensor_from_accel_0 * sensor_axis_sensor_0
                                                        + vertical_sensor_from_accel_1 * sensor_axis_sensor_1
                                                        + vertical_sensor_from_accel_2 * sensor_axis_sensor_2);
                                        // convert to degrees
                                        inclination_angle = Math.toDegrees(inclination_angle);
                                        inclination_angle_from_accel = Math
                                                .toDegrees(inclination_angle_from_accel);

                                        if (inclination_angle > threshold_L && MotorToggle_state == true) {
                                            motor_status = 1;
                                            //board.getModule(Haptic.class).startBuzzer;
                                            metawear.getModule(Haptic.class).startBuzzer((short) 40);
                                        } else {
                                            motor_status = 0;
                                        }

                                        Log.i("MainActivity", Integer.toString(motor_status));
                                        Log.i("MainActivity", Double.toString(inclination_angle));
                                        csv_entry = csv_entry + time_stamp + "," + inclination_angle + ","
                                                + MotorToggle_state + "," + motor_status + ","
                                                + inclination_angle_from_accel + "," + threshold_L + "," + alpha
                                                + "," + accel_string_x + "," + accel_string_y + ","
                                                + accel_string_z + "," + gyro_string_x + "," + gyro_string_y
                                                + "," + gyro_string_z + "\n";
                                    }
                                }
                            }
                        });
                    }
                }).continueWith(new Continuation<Route, Void>() {
                    @Override
                    public Void then(Task<Route> task) throws Exception {
                        gyroscope.angularVelocity().start();
                        gyroscope.start();

                        currentTime = System.currentTimeMillis();
                        previousTime = currentTime;
                        totalTime = 0;
                        return null;
                    }
                });
            } else {
                // Stop all activity
                Log.i("MainActivity", "Stopped");
                ProgramState_status = false;
                accelerometer.stop();
                accelerometer.acceleration().stop();
                gyroscope.stop();
                gyroscope.angularVelocity().stop();
                ProgramState_text.setText("Saved previous data, Ready to Start");

                filename = FileName_text.getText().toString();

                file = new File(ctx.getExternalFilesDir(null), filename);
                try {
                    OutputStream os = new FileOutputStream(file);
                    os.write(csv_entry.getBytes());
                    os.close();
                    Log.i("MainActivity", "File is created as..." + filename);
                } catch (IOException e) {
                    Log.i("MainActivity", "File NOT created ...!");
                    e.printStackTrace();
                }

                // Reinitialize CSV Entry
                csv_entry = "time" + "," + "inclination angle" + "," + "feedback toggle" + "," + "motor status"
                        + "," + "inclination angle from accelerometers" + "," + "threshold" + "," + "alpha"
                        + "," + "accelerometer_x" + "," + "accelerometer_y" + "," + "acceleromter_z" + ","
                        + "gyroscope_x" + "," + "gyroscope_y" + "," + "gyroscope_z" + "\n" + "sec" + "," + "deg"
                        + "," + "binary" + "," + "binary" + "," + "deg" + "," + "deg" + "," + " " + "," + "g"
                        + "," + "g" + "," + "g" + "," + "deg/sec" + "," + "deg/sec" + "," + "deg/sec" + "\n";
                ProgramState_text.setText("Data Saved and Cleared");

                // Ensure the first loop of next trial goes thru accel first
                initial_accel_loop = 1;

                // Next Trial Increment
                TrialNumber_int = TrialNumber_int + 1;
                TrialNumber.setText(TrialNumber_int.toString());
            }
        }
    });
}