create residual graph

@throws UnexpectedValueException if input graph has undirected edges or flow/capacity is not set
@return Graph
@uses Graph::createGraphCloneEdgeless()
@uses Graph::createEdgeClone()
@uses Graph::createEdgeCloneInverted()
544385
public function createGraph()
    {
        $newgraph = $this->graph->createGraphCloneEdgeless();

        foreach ($this->graph->getEdges() as $edge) {
            if (!($edge instanceof EdgeDirected)) {
                throw new UnexpectedValueException('Edge is undirected');
            }

            $flow = $edge->getFlow();
            if ($flow === NULL) {
                throw new UnexpectedValueException('Flow not set');
            }

            $capacity = $edge->getCapacity();
            if ($capacity === NULL) {
                throw new UnexpectedValueException('Capacity not set');
            }

            // capacity is still available, clone remaining capacity into new edge
            if ($this->keepNullCapacity || $flow < $capacity) {
                $newEdge = $newgraph->createEdgeClone($edge)->setFlow(0)->setCapacity($capacity - $flow);

                if ($this->mergeParallelEdges) {
                    $this->mergeParallelEdges($newEdge);
                }
            }

            // flow is set, clone current flow as capacity for back-flow into new inverted edge (opposite direction)
            if ($this->keepNullCapacity || $flow > 0) {
                $newEdge = $newgraph->createEdgeCloneInverted($edge)->setFlow(0)->setCapacity($flow);

                // if weight is set, use negative weight for back-edges
                if ($newEdge->getWeight() !== NULL) {
                    $newEdge->setWeight(-$newEdge->getWeight());
                }

                if ($this->mergeParallelEdges) {
                    $this->mergeParallelEdges($newEdge);
                }
            }
        }

        return $newgraph;
    }
1282950
public static SimpleGraph<String, DefaultEdge> getSimpleGraphFromUser() {
        Scanner sc = new Scanner(System.in);
        SimpleGraph<String, DefaultEdge> graph = new SimpleGraph<String, DefaultEdge>(DefaultEdge.class);

        // input number of vertices
        int verticeAmount;
        do {
            System.out.print("Enter the number of vertices (more than one): ");
            verticeAmount = sc.nextInt();
        } while (verticeAmount <= 1);

        // input vertices
        for (int i = 1; i <= verticeAmount; i++) {
            System.out.print("Enter vertex name " + i + ": ");
            String input = sc.next();
            if (graph.vertexSet().contains(input)) {
                System.err.println("vertex with that name already exists");
                i--;
            } else {
                graph.addVertex(input);
            }
        }

        // input edges
        System.out.println("\nEnter edge (name => name)");
        String userWantsToContinue;
        do {
            String e1, e2;
            
            do {
                System.out.print("Edge from: ");
                e1 = sc.next();
            } while (!graph.vertexSet().contains(e1));
            do {
                System.out.print("Edge to: ");
                e2 = sc.next();
            } while (!graph.vertexSet().contains(e2));

            graph.addEdge(e1, e2);

            // add another edge?
            System.out.print("Add more edges? (y/n): ");
            userWantsToContinue = sc.next();
        }while (userWantsToContinue.equals("y") || userWantsToContinue.equals("yes") || userWantsToContinue.equals("1"));

        return graph;
    }
203151
SimpleEdge tryCreateCachedEdge_(int value) {
		int ind = (value & NumberUtils.intMax()) % m_simple_edges_cache.size();
		SimpleEdge se = m_simple_edges_cache.get(ind);
		if (se == null) {
			if (m_simple_edges_recycle.isEmpty()) {
				// assert(m_simple_edges_buffer.size() <
				// m_simple_edges_buffer.capacity());//should never happen
				// assert(m_simple_edges_buffer.size() <
				// m_simple_edges_cache.size());//should never happen
				m_simple_edges_buffer.add(new SimpleEdge());
				se = m_simple_edges_buffer
						.get(m_simple_edges_buffer.size() - 1);
			} else {
				se = m_simple_edges_recycle
						.get(m_simple_edges_recycle.size() - 1);
				m_simple_edges_recycle
						.remove(m_simple_edges_recycle.size() - 1);
			}

			se.m_value = value;
			m_simple_edges_cache.set(ind, se);
			return se;
		} else {
			assert (se.m_value != value);// do not call TryCreateCachedEdge
											// twice.
		}

		return null;
	}
1367243
public static <N> ImmutableGraph<N> emptyGraph(Graph<N> graph) {
        return ImmutableGraph.copyOf(GraphBuilder.from(graph).build());
    }
65815
@Override
	public DataSet<Vertex<K, VV>> createResult() {
		if (this.initialVertices == null) {
			throw new IllegalStateException("The input data set has not been set.");
		}

		// prepare some type information
		TypeInformation<K> keyType = ((TupleTypeInfo<?>) initialVertices.getType()).getTypeAt(0);
		TypeInformation<Tuple2<K, Message>> messageTypeInfo = new TupleTypeInfo<>(keyType, messageType);

		// create a graph
		Graph<K, VV, EV> graph =
				Graph.fromDataSet(initialVertices, edgesWithValue, initialVertices.getExecutionEnvironment());

		// check whether the numVertices option is set and, if so, compute the total number of vertices
		// and set it within the scatter and gather functions

		DataSet<LongValue> numberOfVertices = null;
		if (this.configuration != null && this.configuration.isOptNumVertices()) {
			try {
				numberOfVertices = GraphUtils.count(this.initialVertices);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (this.configuration != null) {
			scatterFunction.setDirection(this.configuration.getDirection());
		} else {
			scatterFunction.setDirection(EdgeDirection.OUT);
		}

		// retrieve the direction in which the updates are made and in which the messages are sent
		EdgeDirection messagingDirection = scatterFunction.getDirection();

		// check whether the degrees option is set and, if so, compute the in and the out degrees and
		// add them to the vertex value
		if (this.configuration != null && this.configuration.isOptDegrees()) {
			return createResultVerticesWithDegrees(graph, messagingDirection, messageTypeInfo, numberOfVertices);
		} else {
			return createResultSimpleVertex(messagingDirection, messageTypeInfo, numberOfVertices);
		}
	}
711058
public function createVertices($n)
    {
        $vertices = array();
        if (is_int($n) && $n >= 0) {
            for ($id = $this->getNextId(), $n += $id; $id < $n; ++$id) {
                $vertices[$id] = new Vertex($this, $id);
            }
        } elseif (is_array($n)) {
            // array given => check to make sure all given IDs are available (atomic operation)
            foreach ($n as $id) {
                if (!is_int($id) && !is_string($id)) {
                    throw new InvalidArgumentException('All Vertex IDs have to be of type integer or string');
                } elseif ($this->vertices->hasVertexId($id)) {
                    throw new OverflowException('Given array of Vertex IDs contains an ID that already exists. Given IDs must be unique');
                } elseif (isset($vertices[$id])) {
                    throw new InvalidArgumentException('Given array of Vertex IDs contain duplicate IDs. Given IDs must be unique');
                }

                // temporary marker to check for duplicate IDs in the array
                $vertices[$id] = false;
            }

            // actually create all requested vertices
            foreach ($n as $id) {
                $vertices[$id] = new Vertex($this, $id);
            }
        } else {
            throw new InvalidArgumentException('Invalid number of vertices given. Must be non-negative integer or an array of Vertex IDs');
        }

        return new Vertices($vertices);
    }
55704
public function getIterator()
    {

        $result = $this->data !== null ? $this->data : call_user_func($this->getter);

        if (!$result) {
            return new ArrayIterator([]);
        }

        if ($result instanceof Iterator) {
            return $result;
        }

        if (is_array($result)) {
            return new ArrayIterator($result);
        }

        if (!$result instanceof Traversable) {
            throw new UnexpectedValueException('The returned result of the assigned callable is not supported (traversable)');
        }

        $array = [];

        foreach ($result as $item) {
            $array[] = $item;
        }

        return new ArrayIterator($array);
    }
1109954
public function createObjectType() : ObjectConstructorCallbackDefiner
    {
        return new ObjectConstructorCallbackDefiner($this->class, function (callable $typeCallback) {
            $this->createObjectCallback = function (array $input) use ($typeCallback) {
                $className = $this->class->getClassName();

                /** @var ValueObject $valueObject */
                $valueObject = $typeCallback($input);

                if (!($valueObject instanceof $className)) {
                    throw InvalidReturnValueException::format(
                        'Invalid create object callback return value: expecting class compatible with %s, %s given',
                        $className, is_string($valueObject) ? $valueObject : Debug::getType($valueObject)
                    );
                }

                return $valueObject;
            };
        });
    }
101708
public function create()
    {
        $zeroPrice = $this->createZeroAmountMoney();

        /**
         * @var Variant $variant
         */
        $classNamespace = $this->getEntityNamespace();
        $variant = new $classNamespace();
        $variant
            ->setSku('')
            ->setStock(0)
            ->setPrice($zeroPrice)
            ->setReducedPrice($zeroPrice)
            ->setImages(new ArrayCollection())
            ->setOptions(new ArrayCollection())
            ->setWidth(0)
            ->setHeight(0)
            ->setWidth(0)
            ->setDepth(0)
            ->setWeight(0)
            ->setShowInHome(false)
            ->setImagesSort('')
            ->setEnabled(true)
            ->setCreatedAt($this->now());

        return $variant;
    }
1179095
function it_leavesNewEdgeWithNewValue() {
			it("leaves a new edge in the graph with a new value", function () {
				callItWith('k1', 'k2', 'newValue');
				expect(graph.hasEdge('k1', 'k2')).toBeTruthy();
				expect(graph.edgeValue('k1', 'k2')).toBe('newValue');
				expect(graph.edgeCount()).toBe(originalEdgeCount + 1);
			});
		}
218767
function it_leavesNewVertexWithNewValue() {
			it("leaves a new vertex in the graph with a new value", function () {
				callItWith('newKey', 'newValue');
				expect(graph.hasVertex('newKey')).toBeTruthy();
				expect(graph.vertexValue('newKey')).toBe('newValue');
				expect(graph.vertexCount()).toBe(originalVertexCount + 1);
			});
		}
1251368
protected function checkBalance()
    {
        $alg = new AlgorithmFlow($this->graph);
        $balance = $alg->getBalance();

        $tolerance = 0.000001;
        if ($balance >= $tolerance || $balance <= -$tolerance) {
            throw new UnexpectedValueException('The given graph is not balanced value is: ' . $balance);
        }

        return $this;
    }
278084
private function multiPolygon()
    {
        $count  = $this->readCount();
        $values = array();

        for ($i = 0; $i < $count; $i++) {
            $this->readByteOrder();

            $type = $this->readType();

            if ($this->getDimensionedPrimitive(self::WKB_TYPE_POLYGON) !== $type) {
                throw new UnexpectedValueException($this->getBadTypeInTypeMessage($type, self::WKB_TYPE_MULTIPOLYGON, array(self::WKB_TYPE_POLYGON)));
            }

            $values[] = $this->readLinearRings($this->readCount());
        }

        return $values;
    }
53908
public function current()
    {
        if (!isset($this->tokenList[$this->ptr])) {
            throw new \UnexpectedValueException("Unexpected input at offset {$this->ptr}, unexpected end of stream");
        }
        return $this->tokenList[$this->ptr];
    }
782978
public function getInDegree()
    {

        if (!is_a($this->nodeGraph, "\Platform\Graph")):
            throw new \Exception("Unkown node parent graph. Cannot calculate InDegree of NODE:" . $this->getId(), PLATFORM_ERROR); //Unkonwn graph type;
        endif;

        $graph = $this->getGraph();
        $arcIds = $graph->getArcSet();

        //If this graph is undirected, then we can't calculate the  indegree to this node;
        if (empty($arcIds))
            return $this->getDegree();

        $edges = $graph->getEdgeSet();
        $incidence = 0;

        //search for all arcs with this node as tail
        foreach ($arcIds as $arc):
            $edge = $edges[$arc];
            if ($edge->getTail()->getId() == $this->getId()) {
                $incidence++;
                //if head is the same as self, as is the case in cycled edges then we have one more indegree,
                //looped vertices have an indegree of two;
                if ($edge->getHead()->getId() == $this->getId())
                    $incidence++;
            }
        endforeach;

        return $incidence;
    }
988932
private function createNextStatesNodeDefinition()
    {
        $flowTypes = array(
            NextStateInterface::TYPE_STEP,
            NextStateInterface::TYPE_STEP_OR,
            NextStateInterface::TYPE_PROCESS,
        );

        $nextStatesNode = new ArrayNodeDefinition('next_states');

        $nextStatesNode
            ->useAttributeAsKey('name')
            ->prototype('array')
                ->addDefaultsIfNotSet()
                ->children()
                    ->scalarNode('type')
                        ->defaultValue('step')
                        ->validate()
                             ->ifNotInArray($flowTypes)
                             ->thenInvalid('Invalid next element type "%s". Please use one of the following types: '.implode(', ', $flowTypes))
                        ->end()
                    ->end()

                    ->variableNode('target')
                        ->cannotBeEmpty()
                    ->end()
                ->end()
            ->end()
        ;

        return $nextStatesNode;
    }
38976
private static Graph buildGraph() {
        Graph g = new TinkerGraph();
        //add vertices
        Vertex v1 = g.addVertex("v1");
        Vertex v2 = g.addVertex("v2");
        Vertex v3 = g.addVertex("v3");
        Vertex v4 = g.addVertex("v4");
        Vertex v5 = g.addVertex("v5");
        Vertex v6 = g.addVertex("v6");

        //add edges labeled with costs
        Edge e1 = g.addEdge("e1", v1, v2, "(7, 1)");
        e1.setProperty("c1", 7);
        e1.setProperty("c2", 1);

        Edge e2 = g.addEdge("e2", v1, v3, "(1, 4)");
        e2.setProperty("c1", 1);
        e2.setProperty("c2", 4);

        Edge e3 = g.addEdge("e3", v1, v4, "(2, 1)");
        e3.setProperty("c1", 2);
        e3.setProperty("c2", 1);

        Edge e4 = g.addEdge("e4", v2, v4, "(1, 1)");
        e4.setProperty("c1", 1);
        e4.setProperty("c2", 1);

        Edge e5 = g.addEdge("e5", v2, v6, "(2, 1)");
        e5.setProperty("c1", 2);
        e5.setProperty("c2", 1);

        Edge e6 = g.addEdge("e6", v3, v4, "(1, 1)");
        e6.setProperty("c1", 1);
        e6.setProperty("c2", 1);

        Edge e7 = g.addEdge("e7", v4, v5, "(3, 2)");
        e7.setProperty("c1", 3);
        e7.setProperty("c2", 2);

        Edge e8 = g.addEdge("e8", v4, v6, "(4, 8)");
        e8.setProperty("c1", 4);
        e8.setProperty("c2", 8);

        Edge e9 = g.addEdge("e9", v5, v6, "(1, 1)");
        e9.setProperty("c1", 1);
        e9.setProperty("c2", 1);

        return g;
    }