Calculate the slopes and directions based on the 8 sections from
        Tarboton http://www.neng.usu.edu/cee/faculty/dtarb/96wr03137.pdf
557250
def _tarboton_slopes_directions(self, data, dX, dY):
        

        return _tarboton_slopes_directions(data, dX, dY,
                                           self.facets, self.ang_adj)
360880
function calculProgress(navigation, current) {
    var n = _.size(navigation);
    var percent = 0, prevPercent = 0, currentChapter = null;
    var done = true;

    var chapters = _.chain(navigation)

    // Transform as array
    .map(function(nav, path) {
        nav.path = path;
        return nav;
    })

    // Sort entries
    .sortBy(function(nav) {
        return nav.index;
    })

    .map(function(nav, i) {
        // Calcul percent
        nav.percent = (i * 100) / Math.max((n - 1), 1);

        // Is it done
        nav.done = done;
        if (nav.path == current) {
            currentChapter = nav;
            percent = nav.percent;
            done = false;
        } else if (done) {
            prevPercent = nav.percent;
        }

        return nav;
    })
    .value();

    return {
        // Previous percent
        prevPercent: prevPercent,

        // Current percent
        percent: percent,

        // List of chapter with progress
        chapters: chapters,

        // Current chapter
        current: currentChapter
    };
}
278798
def learningCurve(expPath, suite):
  
  print("\nLEARNING CURVE ================",expPath,"=====================")
  try:
    headers=["testerror","totalCorrect","elapsedTime","entropy"]
    result = suite.get_value(expPath, 0, headers, "all")
    info = []
    for i,v in enumerate(zip(result["testerror"],result["totalCorrect"],
                             result["elapsedTime"],result["entropy"])):
      info.append([i, v[0], v[1], int(v[2]), v[3]])
    headers.insert(0,"iteration")
    print(tabulate(info, headers=headers, tablefmt="grid"))
  except:
    print("Couldn't load experiment",expPath)
1174872
def roll(self):
    

    x, y, z, w = self.x, self.y, self.z, self.w
    return math.atan2(2*y*w - 2*x*z, 1 - 2*y*y - 2*z*z)
230124
function generateArcPath (x, y, radius, startAngle, endAngle) {
  var start = polarToCartesian(x, y, radius, startAngle);
  var end = polarToCartesian(x, y, radius, endAngle);
  var arcSweep = endAngle - startAngle <= 180 ? '0' : '1';
  return [
    'M', start.x, start.y,
    'A', radius, radius, 0, arcSweep, 0, end.x, end.y
  ].join(' ');
}
1020783
private void calcZDirection() {
		calcBoundaries();

		// if the longer part of the structure faces towards the back (-z direction),
		// rotate around y-axis so the longer part faces the viewer (+z direction)
		if (Math.abs(minBoundary.z) > Math.abs(maxBoundary.z)) {
			Matrix4d rot = flipY();
			rot.mul(transformationMatrix);
			transformationMatrix.set(rot);
		}
	}
771505
def plot_plates(step, time, vrms_surface, trench, ridge, agetrench,
                topo, fids):
    """"""
    vphi = step.fields['v2'][0, :, :, 0]
    tempfld = step.fields['T'][0, :, :, 0]
    concfld = step.fields['c'][0, :, :, 0]
    timestep = step.isnap

    if step.sdat.par['boundaries']['air_layer']:
        dsa = step.sdat.par['boundaries']['air_thickness']
        # we are a bit below the surface; delete "-some number"
        # to be just below
        # the surface (that is considered plane here); should check if you are
        # in the thermal boundary layer
        indsurf = np.argmin(abs((1 - dsa) - step.geom.r_coord)) - 4
        # depth to detect the continents
        indcont = np.argmin(abs((1 - dsa) - np.array(step.geom.r_coord))) - 10
    else:
        indsurf = -1
        indcont = -1  # depth to detect continents

    if step.sdat.par['boundaries']['air_layer'] and\
       not step.sdat.par['continents']['proterozoic_belts']:
        continents = np.ma.masked_where(
            np.logical_or(concfld[:-1, indcont] < 3,
                          concfld[:-1, indcont] > 4),
            concfld[:-1, indcont])
    elif (step.sdat.par['boundaries']['air_layer'] and
          step.sdat.par['continents']['proterozoic_belts']):
        continents = np.ma.masked_where(
            np.logical_or(concfld[:-1, indcont] < 3,
                          concfld[:-1, indcont] > 5),
            concfld[:-1, indcont])
    elif step.sdat.par['tracersin']['tracers_weakcrust']:
        continents = np.ma.masked_where(
            concfld[:-1, indcont] < 3, concfld[:-1, indcont])
    else:
        continents = np.ma.masked_where(
            concfld[:-1, indcont] < 2, concfld[:-1, indcont])

    # masked array, only continents are true
    continentsall = continents / continents

    ph_coord = step.geom.p_coord

    # velocity
    vph2 = 0.5 * (vphi + np.roll(vphi, 1, 0))  # interpolate to the same phi
    dvph2 = (np.diff(vph2[:, indsurf]) / (ph_coord[0] * 2.))

    # plotting
    fig0, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True, figsize=(12, 8))
    ax1.plot(ph_coord[:-1], concfld[:-1, indsurf], color='g', label='Conc')
    ax2.plot(ph_coord[:-1], tempfld[:-1, indsurf], color='k', label='Temp')
    ax3.plot(ph_coord[:-1], vph2[:-1, indsurf], label='Vel')

    ax1.fill_between(
        ph_coord[:-1], continents, 1., facecolor='#8B6914', alpha=0.2)
    ax2.fill_between(
        ph_coord[:-1], continentsall, 0., facecolor='#8B6914', alpha=0.2)

    tempmin = step.sdat.par['boundaries']['topT_val'] * 0.9\
        if step.sdat.par['boundaries']['topT_mode'] == 'iso' else 0.0
    tempmax = step.sdat.par['boundaries']['botT_val'] * 0.35\
        if step.sdat.par['boundaries']['botT_mode'] == 'iso' else 0.8

    ax2.set_ylim(tempmin, tempmax)
    ax3.fill_between(
        ph_coord[:-1], continentsall * round(1.5 * np.amax(dvph2), 1),
        round(np.amin(dvph2) * 1.1, 1), facecolor='#8B6914', alpha=0.2)
    ax3.set_ylim(conf.plates.vmin, conf.plates.vmax)

    ax1.set_ylabel("Concentration")
    ax2.set_ylabel("Temperature")
    ax3.set_ylabel("Velocity")
    ax1.set_title(timestep)
    ax1.text(0.95, 1.07, str(round(time, 0)) + ' My',
             transform=ax1.transAxes)
    ax1.text(0.01, 1.07, str(round(step.geom.ti_ad, 8)),
             transform=ax1.transAxes)

    plot_plate_limits(ax3, ridge, trench, conf.plates.vmin,
                      conf.plates.vmax)

    misc.saveplot(fig0, 'sveltempconc', timestep)

    # plotting velocity and velocity derivative
    fig0, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(12, 8))
    ax1.plot(ph_coord[:-1], vph2[:-1, indsurf], label='Vel')
    ax1.axhline(y=0, xmin=0, xmax=2 * np.pi,
                color='black', ls='solid', alpha=0.2)
    ax1.set_ylabel("Velocity")
    ax1.text(0.95, 1.07, str(round(time, 0)) + ' My',
             transform=ax1.transAxes)
    ax1.text(0.01, 1.07, str(round(step.geom.ti_ad, 8)),
             transform=ax1.transAxes)
    ax2.plot(ph_coord[:-1] + ph_coord[0], dvph2, color='k', label='dv')
    ax2.set_ylabel("dv")

    plot_plate_limits(ax1, ridge, trench, conf.plates.vmin,
                      conf.plates.vmax)
    plot_plate_limits(ax2, ridge, trench, conf.plates.dvmin,
                      conf.plates.dvmax)
    ax1.set_xlim(0, 2 * np.pi)
    ax1.set_title(timestep)

    ax1.fill_between(
        ph_coord[:-1], continentsall * conf.plates.vmin, conf.plates.vmax,
        facecolor='#8b6914', alpha=0.2)
    ax1.set_ylim(conf.plates.vmin, conf.plates.vmax)
    ax2.fill_between(
        ph_coord[:-1], continentsall * conf.plates.dvmin,
        conf.plates.dvmax, facecolor='#8b6914', alpha=0.2)
    ax2.set_ylim(conf.plates.dvmin, conf.plates.dvmax)

    misc.saveplot(fig0, 'sveldvel', timestep)

    # plotting velocity and second invariant of stress
    if 'str' in conf.plates.plot:
        stressfld = step.fields['sII'][0, :, :, 0]
        fig0, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(12, 8))
        ax1.plot(ph_coord[:-1], vph2[:-1, indsurf], label='Vel')
        ax1.axhline(y=0, xmin=0, xmax=2 * np.pi,
                    color='black', ls='solid', alpha=0.2)
        ax1.set_ylabel("Velocity")
        ax1.text(0.95, 1.07, str(round(time, 0)) + ' My',
                 transform=ax1.transAxes)
        ax1.text(0.01, 1.07, str(round(step.geom.ti_ad, 8)),
                 transform=ax1.transAxes)
        ax2.plot(ph_coord[:-1],
                 stressfld[:-1, indsurf] * step.sdat.scales.stress / 1.e6,
                 color='k', label='Stress')
        ax2.set_ylim(conf.plates.stressmin, conf.plates.stressmax)
        ax2.set_ylabel("Stress [MPa]")

        plot_plate_limits(ax1, ridge, trench,
                          conf.plates.vmin, conf.plates.vmax)
        plot_plate_limits(ax2, ridge, trench,
                          conf.plates.stressmin, conf.plates.stressmax)
        ax1.set_xlim(0, 2 * np.pi)
        ax1.set_title(timestep)

        ax1.fill_between(
            ph_coord[:-1], continentsall * conf.plates.vmin,
            conf.plates.vmax, facecolor='#8B6914', alpha=0.2)
        ax1.set_ylim(conf.plates.vmin, conf.plates.vmax)
        ax2.fill_between(
            ph_coord[:-1], continentsall * conf.plates.dvmin,
            conf.plates.dvmax,
            facecolor='#8B6914', alpha=0.2)

        misc.saveplot(fig0, 'svelstress', timestep)

    # plotting velocity
    fig1, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(12, 8))
    ax1.plot(ph_coord[:-1], vph2[:-1, indsurf], label='Vel')
    ax1.axhline(y=0, xmin=0, xmax=2 * np.pi,
                color='black', ls='solid', alpha=0.2)
    ax1.set_ylim(conf.plates.vmin, conf.plates.vmax)
    ax1.set_ylabel("Velocity")
    ax1.text(0.95, 1.07, str(round(time, 0)) + ' My',
             transform=ax1.transAxes)
    plot_plate_limits(ax1, ridge, trench, conf.plates.vmin,
                      conf.plates.vmax)

    # plotting velocity and age at surface
    if 'age' in conf.plates.plot:
        agefld = step.fields['age'][0, :, :, 0]
        age_surface = np.ma.masked_where(
            agefld[:, indsurf] < 0.00001, agefld[:, indsurf])
        age_surface_dim = (age_surface * vrms_surface * conf.scaling.ttransit /
                           conf.scaling.yearins / 1.e6)

        fig2, (ax3, ax4) = plt.subplots(2, 1, sharex=True, figsize=(12, 8))
        ax3.plot(ph_coord[:-1], vph2[:-1, indsurf], label='Vel')
        ax3.axhline(
            y=0, xmin=0, xmax=2 * np.pi,
            color='black', ls='solid', alpha=0.2)
        ax3.set_ylim(conf.plates.vmin, conf.plates.vmax)
        ax3.set_ylabel("Velocity")
        ax3.text(0.95, 1.07, str(round(time, 0)) + ' My',
                 transform=ax3.transAxes)
        ax3.fill_between(
            ph_coord[:-1], continentsall * conf.plates.vmax,
            conf.plates.vmin, facecolor='#8B6914', alpha=0.2)
        plot_plate_limits(ax3, ridge, trench,
                          conf.plates.vmin, conf.plates.vmax)

    times_subd = []
    age_subd = []
    distance_subd = []
    ph_trench_subd = []
    ph_cont_subd = []
    if step.sdat.par['switches']['cont_tracers']:
        for i, trench_i in enumerate(trench):
            # detection of the distance in between subduction and continent
            ph_coord_noend = ph_coord[:-1]
            angdistance1 = abs(ph_coord_noend[continentsall == 1] - trench_i)
            angdistance2 = 2. * np.pi - angdistance1
            angdistance = np.minimum(angdistance1, angdistance2)
            distancecont = min(angdistance)
            argdistancecont = np.argmin(angdistance)
            continentpos = ph_coord_noend[continentsall == 1][argdistancecont]

            ph_trench_subd.append(trench_i)
            age_subd.append(agetrench[i])
            ph_cont_subd.append(continentpos)
            distance_subd.append(distancecont)
            times_subd.append(step.geom.ti_ad)

            if angdistance1[argdistancecont] < angdistance2[argdistancecont]:
                if continentpos - trench_i < 0:  # continent is on the left
                    distancecont = - distancecont
                ax1.annotate('', xy=(trench_i + distancecont, 2000),
                             xycoords='data', xytext=(trench_i, 2000),
                             textcoords='data',
                             arrowprops=dict(arrowstyle="->", lw="2",
                                             shrinkA=0, shrinkB=0))
            else:  # distance over boundary
                xy_anot, xy_text = 0, 2 * np.pi
                if continentpos - trench_i < 0:
                    xy_anot, xy_text = xy_text, xy_anot
                ax1.annotate('', xy=(xy_anot, 2000),
                             xycoords='data', xytext=(trench_i, 2000),
                             textcoords='data',
                             arrowprops=dict(arrowstyle="-", lw="2",
                                             shrinkA=0, shrinkB=0))
                ax1.annotate('', xy=(continentpos, 2000),
                             xycoords='data', xytext=(xy_text, 2000),
                             textcoords='data',
                             arrowprops=dict(arrowstyle="->", lw="2",
                                             shrinkA=0, shrinkB=0))

    ax1.fill_between(
        ph_coord[:-1], continentsall * conf.plates.vmin,
        conf.plates.vmax, facecolor='#8B6914', alpha=0.2)
    ax2.set_ylabel("Topography [km]")
    ax2.axhline(y=0, xmin=0, xmax=2 * np.pi,
                color='black', ls='solid', alpha=0.2)
    ax2.plot(topo[:, 0],
             topo[:, 1] * step.sdat.scales.length / 1.e3,
             color='black')
    ax2.set_xlim(0, 2 * np.pi)
    ax2.set_ylim(conf.plates.topomin, conf.plates.topomax)
    ax2.fill_between(
        ph_coord[:-1], continentsall * conf.plates.topomax,
        conf.plates.topomin, facecolor='#8B6914', alpha=0.2)
    plot_plate_limits(ax2, ridge, trench, conf.plates.topomin,
                      conf.plates.topomax)
    ax1.set_title(timestep)
    misc.saveplot(fig1, 'sveltopo', timestep)

    if 'age' in conf.plates.plot:
        ax4.set_ylabel("Seafloor age [My]")
        # in dimensions
        ax4.plot(ph_coord[:-1], age_surface_dim[:-1], color='black')
        ax4.set_xlim(0, 2 * np.pi)
        ax4.fill_between(
            ph_coord[:-1], continentsall * conf.plates.agemax,
            conf.plates.agemin, facecolor='#8B6914', alpha=0.2)
        ax4.set_ylim(conf.plates.agemin, conf.plates.agemax)
        plot_plate_limits(ax4, ridge, trench, conf.plates.agemin,
                          conf.plates.agemax)
        ax3.set_title(timestep)
        misc.saveplot(fig2, 'svelage', timestep)

    # writing the output into a file, all time steps are in one file
    for isubd in np.arange(len(distance_subd)):
        fids[1].write("%6.0f %11.7f %11.3f %10.6f %10.6f %10.6f %11.3f\n" % (
            timestep,
            times_subd[isubd],
            time,
            distance_subd[isubd],
            ph_trench_subd[isubd],
            ph_cont_subd[isubd],
            age_subd[isubd],
        ))
1306813
def click_estimate_slope():
    

    c1 = _pylab.ginput()
    if len(c1)==0:
        return None

    c2 = _pylab.ginput()
    if len(c2)==0:
        return None

    return (c1[0][1]-c2[0][1])/(c1[0][0]-c2[0][0])
292880
function calculateLegacyCurvePoints(datapoints, curvedLinesOptions, yPos) {

			var points = datapoints.points;
			var ps = datapoints.pointsize;
			var num = Number(curvedLinesOptions.curvePointFactor) * (points.length / ps);

			var xdata = new Array;
			var ydata = new Array;

			var curX = -1;
			var curY = -1;
			var j = 0;

			if (curvedLinesOptions.fit) {
				//insert a point before and after the "real" data point to force the line
				//to have a max,min at the data point.

				var fpDist;
				if ( typeof curvedLinesOptions.fitPointDist == 'undefined') {
					//estimate it
					var minX = points[0];
					var maxX = points[points.length - ps];
					fpDist = (maxX - minX) / (500 * 100);
					//x range / (estimated pixel length of placeholder * factor)
				} else {
					//use user defined value
					fpDist = Number(curvedLinesOptions.fitPointDist);
				}

				for (var i = 0; i < points.length; i += ps) {

					var frontX;
					var backX;
					curX = i;
					curY = i + yPos;

					//add point X s
					frontX = points[curX] - fpDist;
					backX = points[curX] + fpDist;

					var factor = 2;
					while (frontX == points[curX] || backX == points[curX]) {
						//inside the ulp
						frontX = points[curX] - (fpDist * factor);
						backX = points[curX] + (fpDist * factor);
						factor++;
					}

					//add curve points
					xdata[j] = frontX;
					ydata[j] = points[curY];
					j++;

					xdata[j] = points[curX];
					ydata[j] = points[curY];
					j++;

					xdata[j] = backX;
					ydata[j] = points[curY];
					j++;
				}
			} else {
				//just use the datapoints
				for (var i = 0; i < points.length; i += ps) {
					curX = i;
					curY = i + yPos;

					xdata[j] = points[curX];
					ydata[j] = points[curY];
					j++;
				}
			}

			var n = xdata.length;

			var y2 = new Array();
			var delta = new Array();
			y2[0] = 0;
			y2[n - 1] = 0;
			delta[0] = 0;

			for (var i = 1; i < n - 1; ++i) {
				var d = (xdata[i + 1] - xdata[i - 1]);
				if (d == 0) {
					//point before current point and after current point need some space in between
					return [];
				}

				var s = (xdata[i] - xdata[i - 1]) / d;
				var p = s * y2[i - 1] + 2;
				y2[i] = (s - 1) / p;
				delta[i] = (ydata[i + 1] - ydata[i]) / (xdata[i + 1] - xdata[i]) - (ydata[i] - ydata[i - 1]) / (xdata[i] - xdata[i - 1]);
				delta[i] = (6 * delta[i] / (xdata[i + 1] - xdata[i - 1]) - s * delta[i - 1]) / p;
			}

			for (var j = n - 2; j >= 0; --j) {
				y2[j] = y2[j] * y2[j + 1] + delta[j];
			}

			//   xmax  - xmin  / #points
			var step = (xdata[n - 1] - xdata[0]) / (num - 1);

			var xnew = new Array;
			var ynew = new Array;
			var result = new Array;

			xnew[0] = xdata[0];
			ynew[0] = ydata[0];

			result.push(xnew[0]);
			result.push(ynew[0]);

			for ( j = 1; j < num; ++j) {
				//new x point (sampling point for the created curve)
				xnew[j] = xnew[0] + j * step;

				var max = n - 1;
				var min = 0;

				while (max - min > 1) {
					var k = Math.round((max + min) / 2);
					if (xdata[k] > xnew[j]) {
						max = k;
					} else {
						min = k;
					}
				}

				//found point one to the left and one to the right of generated new point
				var h = (xdata[max] - xdata[min]);

				if (h == 0) {
					//similar to above two points from original x data need some space between them
					return [];
				}

				var a = (xdata[max] - xnew[j]) / h;
				var b = (xnew[j] - xdata[min]) / h;

				ynew[j] = a * ydata[min] + b * ydata[max] + ((a * a * a - a) * y2[min] + (b * b * b - b) * y2[max]) * (h * h) / 6;

				result.push(xnew[j]);
				result.push(ynew[j]);
			}

			return result;
		}
164521
def step(self, y, u, t, h):
		
		k1 = h * self.func(t, y, u)
		k2 = h * self.func(t + .5*h, y + .5*h*k1, u)
		k3 = h * self.func(t + .5*h, y + .5*h*k2, u)
		k4 = h * self.func(t + h, y + h*k3, u)
		return y + (k1 + 2*k2 + 2*k3 + k4) / 6.0
1094124
def cart2spol(X):
    
    x,y,z,vx,vy,vz=X
    r=np.sqrt(x*x+y*y+z*z)
    p=np.arctan2(y,x)
    t=np.arccos(z/r)
    vr=(vx*np.cos(p)+vy*np.sin(p))*np.sin(t)+np.cos(t)*vz
    vp=-vx*np.sin(p)+vy*np.cos(p)
    vt=(vx*np.cos(p)+vy*np.sin(p))*np.cos(t)-np.sin(t)*vz
    return np.array([r,p,t,vr,vp,vt])
864241
private void calcCurrentItem() {
        int pointerAngle;

        // calculate the correct pointer angle, depending on clockwise drawing or not
        if(mOpenClockwise) {
            pointerAngle = (mIndicatorAngle + 360 - mPieRotation) % 360;
        }
        else {
            pointerAngle = (mIndicatorAngle + 180 + mPieRotation) % 360;
        }

        for (int i = 0; i < mPieData.size(); ++i) {
            PieModel model = mPieData.get(i);
            if (model.getStartAngle() <= pointerAngle && pointerAngle <= model.getEndAngle()) {
                if (i != mCurrentItem) {
                    setCurrentItem(i, false);
                }
                break;
            }
        }
    }
220751
public function calculate()
    {
        // The slopes array will be a list of slopes between all pairs of points
        $slopes = [];
        $n      = count($this->points);
        for ($i = 0; $i < $n; $i++) {
            for ($j = $i + 1; $j < $n; $j++) {
                $pointi   = $this->points[$i];
                $pointj   = $this->points[$j];
                if ($pointj[0] != $pointi[0]) {
                    $slopes[] = ($pointj[1] - $pointi[1]) / ($pointj[0] - $pointi[0]);
                }
            }
        }

        $this->m = Average::median($slopes);
        $this->b = Average::median($this->ys) - ($this->m * Average::median($this->xs));

        $this->parameters = [$this->b, $this->m];
    }
1135686
function forward$10(p) {
        var gfi, u, deltav, s, d, eps, ro;
        var lon = p.x;
        var lat = p.y;
        var delta_lon = adjust_lon(lon - this.long0);
        /* Transformation */
        gfi = Math.pow(((1 + this.e * Math.sin(lat)) / (1 - this.e * Math.sin(lat))), (this.alfa * this.e / 2));
        u = 2 * (Math.atan(this.k * Math.pow(Math.tan(lat / 2 + this.s45), this.alfa) / gfi) - this.s45);
        deltav = -delta_lon * this.alfa;
        s = Math.asin(Math.cos(this.ad) * Math.sin(u) + Math.sin(this.ad) * Math.cos(u) * Math.cos(deltav));
        d = Math.asin(Math.cos(u) * Math.sin(deltav) / Math.cos(s));
        eps = this.n * d;
        ro = this.ro0 * Math.pow(Math.tan(this.s0 / 2 + this.s45), this.n) / Math.pow(Math.tan(s / 2 + this.s45), this.n);
        p.y = ro * Math.cos(eps) / 1;
        p.x = ro * Math.sin(eps) / 1;

        if (!this.czech) {
            p.y *= -1;
            p.x *= -1;
        }
        return (p);
    }
126866
function _EllipseArc($x0, $y0, $rx, $ry, $seg = 1, $part = false, $start = false)
	{
		// Anticlockwise segment 1-4 TR-TL-BL-BR (part=1 or 2)
		$s = '';

		if ($rx < 0) {
			$rx = 0;
		}

		if ($ry < 0) {
			$ry = 0;
		}

		$rx *= Mpdf::SCALE;
		$ry *= Mpdf::SCALE;

		$astart = 0;

		if ($seg == 1) { // Top Right
			$afinish = 90;
			$nSeg = 4;
		} elseif ($seg == 2) { // Top Left
			$afinish = 180;
			$nSeg = 8;
		} elseif ($seg == 3) { // Bottom Left
			$afinish = 270;
			$nSeg = 12;
		} else {   // Bottom Right
			$afinish = 360;
			$nSeg = 16;
		}

		$astart = deg2rad((float) $astart);
		$afinish = deg2rad((float) $afinish);

		$totalAngle = $afinish - $astart;
		$dt = $totalAngle / $nSeg; // segment angle
		$dtm = $dt / 3;
		$x0 *= Mpdf::SCALE;
		$y0 = ($this->h - $y0) * Mpdf::SCALE;
		$t1 = $astart;
		$a0 = $x0 + ($rx * cos($t1));
		$b0 = $y0 + ($ry * sin($t1));
		$c0 = -$rx * sin($t1);
		$d0 = $ry * cos($t1);
		$op = false;

		for ($i = 1; $i <= $nSeg; $i++) {
			// Draw this bit of the total curve
			$t1 = ($i * $dt) + $astart;
			$a1 = $x0 + ($rx * cos($t1));
			$b1 = $y0 + ($ry * sin($t1));
			$c1 = -$rx * sin($t1);
			$d1 = $ry * cos($t1);
			if ($i > ($nSeg - 4) && (!$part || ($part == 1 && $i <= $nSeg - 2) || ($part == 2 && $i > $nSeg - 2))) {
				if ($start && !$op) {
					$s .= sprintf('%.3F %.3F m ', $a0, $b0);
				}
				$s .= sprintf('%.3F %.3F %.3F %.3F %.3F %.3F c ', ($a0 + ($c0 * $dtm)), ($b0 + ($d0 * $dtm)), ($a1 - ($c1 * $dtm)), ($b1 - ($d1 * $dtm)), $a1, $b1);
				$op = true;
			}
			$a0 = $a1;
			$b0 = $b1;
			$c0 = $c1;
			$d0 = $d1;
		}

		return $s;
	}
380628
def get_notes():
    

    notes = {'DPhi':{}, 'dPhi':{}}
    # Toroidal width (mm, inner outer)
    notes['DPhi']['In'] = 26.370
    notes['DPhi']['Out'] = 31.929

    # Inter tiles distance (mm, uniform)
    notes['dl'] = 0.500

    # Poloidal/Radial total length (mm)
    notes['DL'] = 437.000

    # Number of tiles radially
    notes['nb'] = 35
    notes['nbPhi'] = 19*2*12

    # Radial length of a tile (mm, uniform)
    notes['Dl'] = 12.000

    # Vertical height of tiles (mm, uniform)
    notes['DZ'] = 26.000

    # Toroidal space between needles (mm, inner outer)
    notes['dPhi']['In'] = 0.588
    notes['dPhi']['Out'] = 0.612

    # (X,Z,Y) polygon of one needle (mm) !!!!!! (X,Z,Y)
    # 1 mm should be added towards Z>0 in the direction normal to the divertor's upper surface
    notes['sampleXZY'] = [[-759.457, -625.500, -1797.591], # Old start point
                          [-759.603, -624.572, -1797.936], # Only for pattern
                          [-772.277, -620.864, -1794.112],
                          [-761.681, -610.036, -1769.498], # Computed,tube/plane
                          [-761.895, -620.231, -1764.921],
                          [-751.095, -609.687, -1741.154],
                          [-755.613, -580.944, -1751.852],
                          [-766.413, -591.488, -1775.620], # Edge of plane
                          [-763.902, -596.129, -1774.659], # Computed,tube/plane
                          [-774.498, -606.956, -1799.274], # Middle top of tube
                          [-763.246, -601.395, -1806.563],
                          [-767.575, -605.891, -1816.813],
                          [-763.932, -629.068, -1808.186],
                          [-764.112, -629.255, -1808.613],
                          [-767.755, -606.078, -1817.240],
                          [-772.084, -610.573, -1827.490],
                          [-768.441, -633.750, -1818.863],
                          [-768.622, -633.938, -1819.290],
                          [-772.265, -610.760, -1827.917],
                          [-776.594, -615.256, -1838.167],
                          [-772.950, -638.433, -1829.540],
                          [-773.131, -638.620, -1829.967],
                          [-776.774, -615.443, -1838.594],
                          [-781.103, -619.938, -1848.844],
                          [-777.460, -643.115, -1840.217],
                          [-777.640, -643.303, -1840.644],
                          [-781.283, -620.126, -1849.271],
                          [-785.612, -624.621, -1859.520],
                          [-781.969, -647.798, -1850.894],
                          [-782.149, -647.985, -1851.321],
                          [-785.793, -624.808, -1859.948],
                          [-790.122, -629.303, -1870.197],
                          [-786.478, -652.481, -1861.571],
                          [-786.659, -652.668, -1861.998],
                          [-790.302, -629.491, -1870.624],
                          [-794.631, -633.986, -1880.874],
                          [-790.988, -657.163, -1872.248],
                          [-791.168, -657.351, -1872.675],
                          [-794.811, -634.173, -1881.301]]
    notes['sampleXZY'] = np.array(notes['sampleXZY'])

    for kk in notes.keys():
        if type(notes[kk]) is dict:
            notes[kk]['In'] = notes[kk]['In']*1.e-3
            notes[kk]['Out'] = notes[kk]['Out']*1.e-3
        elif not 'nb' in kk:
            notes[kk] = notes[kk]*1.e-3
    return notes
1241231
def _central_slopes_directions(self, data, dX, dY):
        
        shp = np.array(data.shape) - 1

        direction = np.full(data.shape, FLAT_ID_INT, 'float64')
        mag = np.full(direction, FLAT_ID_INT, 'float64')

        ind = 0
        d1, d2, theta = _get_d1_d2(dX, dY, ind, [0, 1], [1, 1], shp)
        s2 = (data[0:-2, 1:-1] - data[2:, 1:-1]) / d2
        s1 = -(data[1:-1, 0:-2] - data[1:-1, 2:]) / d1
        direction[1:-1, 1:-1] = np.arctan2(s2, s1) + np.pi
        mag = np.sqrt(s1**2 + s2**2)

        return mag, direction