number of segments is too large for given angle and radius как исправить
number of segment is too large for given radius
What can I do for this error?
Number of segments is too large for the given angle and radius.
After that I can see the arc segments are not united, they are all separated automatically.
1 Answer 1
Number of segments is too large for the given angle and radius.
This happens when the arc is very small and the segments would need to be too small to draw. Solution is to either lower the number of segments (type the number of segments you want before drawing the arc), or scaling the model up, drawing the arc, then returning the model to it’s original scale.
I would recommend scaling your entire model up by 100, draw your arc(s), then scale your model by 0.01 to return it to it’s original scale.
Not the answer you’re looking for? Browse other questions tagged sketchup or ask your own question.
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Помоги компилятору помочь тебе
Предисловие
Современные компиляторы обладают огромным количеством диагностик. И удивительно, что очень малая их часть включена по умолчанию.
Огромное количество претензий, которые предъявляют к языку C++ в этих ваших интернетах, — про сложность, небезопасность, стрельбу по ногам и т.п., — относятся как раз к тем случаям, когда люди просто не знают о том, что можно решить эти проблемы лёгким движением пальцев по клавиатуре.
Давайте же исправим эту вопиющую несправедливость, и прольём свет истины на возможности компилятора по предотвращению ошибок.
Содержание
Ода компилятору
Компилятор – лучший друг плюсовика. Компилятор — это не просто транслятор формального человекочитаемого языка в машинные коды. Компилятор — лучший помощник в написании программ.
Важная (и не единственная) помощь, которую оказывает компилятор — поиск ошибок. И я говорю не об опечатках, несовпадении типов и прочих синтаксических ошибках. Я говорю об огромном наборе ошибок, которые можно выловить с помощью механизма предупреждений.
Часто встречаю мнение о том, что предупреждений слишком много, они дают ложноположительные результаты, мешают работать, замыливают глаз, отвлекают от «настоящих» ошибок и т.п. Такое действительно бывает, но это большая редкость.
Игнорировать нельзя исправить
Большинство предупреждений — это не «бзик» компилятора, который можно просто проигнорировать. Предупреждение — это потенциальная ошибка. Предупреждение — это сигнал от компилятора о том, что написано одно, а требуется, возможно, что-то совершенно иное.
Поэтому программист должен помочь компилятору понять, как трактовать спорную ситуацию. То есть либо поправить свою ошибку, либо сообщить компилятору явно о том, что нужно верить программисту и делать именно то, что написано. Причём это поможет не только компилятору, но и человеку, который будет читать код. Лишний static_cast или пара скобок будут явно свидетельствовать о том, что имелось в виду именно то, что написано.
Далее я расскажу о наиболее важных на мой взгляд предупреждениях и покажу, какие ошибки можно отловить с их помощью.
Надеюсь, что данное не слишком занимательное чтиво поможет правильно поставить запятую в заголовке этого раздела.
Сразу хочу оговориться, что далее речь пойдёт исключительно о языке C++ и компиляторе GCC (впрочем, подавляющая часть информации актуальна и для компилятора Clang). Информацию о других компиляторах и языках придётся искать в соответствующих справочниках.
-Wall — это «агрегатор» базовых предупреждений. В языке C++ он включает в себя длинный перечень предупреждений, каждое из которых будет рассмотрено отдельно (на самом деле, рассмотрены будут не все, а только те, которые непосредственно помогают выявлять ошибки).
Несмотря на название, этот флаг включает далеко не все предупреждения, которые умеет обнаруживать компилятор.
-Waddress
Предупреждает о странной работе с адресами. Например, об использовании адреса функции в условном выражении. Такое может произойти, если забыть поставить скобки после имени функции:
Также этот флаг может спасти от типичной ошибки новичка — сравнения строкового литерала с адресом. Очевидно, программист хотел сравнить строки, но в результате сравнил два указателя:
-Warray-bounds=1
-Wbool-compare
Предупреждает о сравнении булева выражения с целым числом, которое нельзя трактовать как булево:
-Wbool-operation
Предупреждает о подозрительных операциях с булевыми выражениями. Например, о побитовом отрицании:
Что касается инкрементов и декрементов булевых переменных, то в C++17 это просто ошибки, безо всяких предупреждений.
-Wcatch-value
Предупреждает о обработчиках исключений, которые принимают полиморфные объекты по значению:
-Wchar-subscripts
-Wcomment
Предупреждает о наличии последовательности, начинающей новый комментарий ( /* ), внутри многострочного комментария, либо о разрыве строки при помощи обратного слеша внутри однострочного комментария.
-Wint-in-bool-context
Предупреждает о подозрительном использовании целых чисел там, где ожидаются булевы выражения, например, в условных выражениях:
Другой пример — операции побитового сдвига в булевом контексте. Вполне вероятно, что здесь произошла опечатка, и имелся в виду не сдвиг, а сравнение:
А также сообщает о любых видах умножения в булевом контексте.
-Winit-self
-Wlogical-not-parentheses
Предупреждает об использовании логического отрицания в левой части сравнения. При этом если правая часть сравнения является сама по себе булевым выражением, то предупреждения не будет.
Используется для того, чтобы отлавливать подозрительные конструкции вроде следующей:
Традиционный способ сообщить компилятору, что так и было задумано — поставить скобки, о чём и сообщает компилятор.
-Wmaybe-uninitialized
Предупреждает о том, что существует возможность использования непроинициализированной переменной.
В данном конкретном случае решается с помощью конструкции default :
-Wmemset-elt-size
-Wmemset-transposed-args
Предупреждает о том, что пользователь, вероятно, перепутал порядок аргументов в функции memset :
-Wmisleading-indentation
-Wmissing-attributes
Предупреждает о ситуации, когда специализация шаблона объявлена не с тем же списком атрибутов, что и оригинальный шаблон.
-Wmultistatement-macros
-Wnonnull
-Wnonnull-compare
-Wparentheses
Типичный случай — опечатались, и вместо равенства написали присвоение:
Компилятор, естественно, сомневается:
Либо исправляем код, либо убеждаем компилятор в том, что мы хотели именно присвоение:
-Wpessimizing-move
Иногда явная попытка переноса может ухудшить производительность. Пример:
-Wreorder
Предупреждает о том, что порядок инициализации членов класса не соответствует порядку их объявления. Поскольку компилятор может переупорядочить инициализацию этих членов, результат может быть неочевидным.
-Wreturn-type
Предупреждает о том, что из функции не вернули заявленный результат:
-Wsequence-point
Сообщает о подозрительных операциях относительно точек следования. Любимый пример (никогда так не делайте):
-Wsign-compare
Одно из важнейших предупреждений. Сообщает о сравнении знаковых и беззнаковых чисел, которое может произвести некорректный результат из-за неявных преобразований. К примеру, отрицательное знаковое число неявно приводится к беззнаковому и внезапно становится положительным:
-Wsizeof-pointer-div
-Wsizeof-pointer-memaccess
-Wstrict-aliasing
Каламбур типизации (strict aliasing) — это отдельная большая тема для разговора. Предлагаю читателю найти литературу по этой теме самостоятельно.
В общем, это тоже крайне полезное предупреждение.
-Wswitch
Предупреждает о том, что не все элементы перечисления задействованы в конструкции switch :
-Wtautological-compare
Предупреждает о бессмысленном сравнении переменной с самой собой:
Кроме того, сообщает о сравнениях при участии битовых операций, которые имеют всегда один и тот же результат (всегда истинно или всегда ложно):
-Wtrigraphs
Предупреждает о наличии триграфов, которые могут изменить смысл программы. Не сообщается о триграфах в теле комментария, за исключением случаев, когда триграф трактуется как перевод строки.
-Wuninitialized
Предупреждает об использовании переменных и членов класса, которые не были проинициализированы:
-Wunused-function
-Wunused-variable
Предупреждает о том, что переменная не используется.
Для того, чтобы помочь компилятору понять, что так и задумывалось, можно использовать конструкцию static_cast (. ) :
-Wextra
-Wempty-body
-Wimplicit-fallthrough
Предупреждает о «проваливании» в операторе switch :
В C++17 для обозначения явного намерения появился специальный атрибут — fallthrough :
-Wmissing-field-initializers
Предупреждает о том, что отдельные члены структуры не были проинициализированы. Скорее всего это просто забыли сделать:
-Wredundant-move
Предупреждает о ненужном вызове std::move в случаях, когда компилятор сам сделает всё, что нужно:
-Wtype-limits
Предупреждает о сравнениях, которые всегда имеют один и тот же результат. Например, когда беззнаковое число проверяется на неотрицательность. Если программист делает такую проверку, то, видимо, предполагает, что число в теории может быть отрицательным, однако, это не так. Видимо, он где-то ошибся:
-Wshift-negative-value
Предупреждает об операциях сдвига для отрицательных значений. Отрицательными могут быть только знаковые числа, а для них это некорректно:
-Wunused-parameter
Предупреждает о неиспользуемом параметре функции. Возможно, про него просто забыли, и в этом случае функция может работать некорректно.
В C++17 для явного выражения намерения существует атрибут maybe_unused :
-Wunused-but-set-parameter
Предупреждает о том, что в параметр функции было записано значение, но после этого он ни разу не использовался. Возможно, про него снова забыли:
-Wpedantic
Нужно больше предупреждений
Но и это ещё не всё. Есть несколько флагов, которые почему-то не входят ни в один из «аргегаторов», но крайне важны и полезны.
-Wctor-dtor-privacy
Предупреждает о том, что класс выглядит неиспользуемым, потому что конструкторы и деструкторы закрыты, а друзей и открытых статических функций-членов у него нет.
Аналогично, сообщает, что у класса есть закрытые функции-члены, а открытых нет ни одной.
-Wnon-virtual-dtor
Предупреждает о том, что у класса есть виртуальные функции-члены, но деструктор при этом не виртуальный. Очень сложно представить себе такой класс. Вероятнее всего, это ошибка.
-Wold-style-cast
-Woverloaded-virtual
Предупреждает о попытке в классе-наследнике перегрузить виртуальную функцию базового класса:
-Wsign-promo
Крайне полезный флаг. Предупреждает о неочевидном выборе перегруженной функции:
Вероятнее всего, хотели-таки позвать вторую перегрузку, а не первую. А если всё-таки первую, то будьте любезны сказать об этом явно.
-Wduplicated-branches
Предупреждает о том, что ветви if и else одинаковы:
-Wduplicated-cond
Предупреждает об одинаковых условиях в цепочках if-else-if :
-Wfloat-equal
Предупреждает о проверке на равенство между двумя числами с плавающей точкой. Скорее всего, это ошибка, и сравнение нужно проводить с заданной точностью.
-Wshadow=compatible-local
Полезная опция, которая не даёт перекрыть локальную переменную другой локальной переменной при условии, что они имеют совместимые типы.
-Wcast-qual
-Wconversion
Очень, очень, очень важный флаг. Он предупреждает об огромном количестве неявных сужающих (то есть потенциально приводящих к потере информации) преобразований, которые могут быть следствием ошибки программиста. Например:
Если вы раньше никогда не включали этот флаг, то будет интересно.
-Wzero-as-null-pointer-constant
-Wextra-semi
Флаг для педантов. Сообщает о лишней точке с запятой после определения функции-члена.
-Wsign-conversion
-Wlogical-op
Предупреждает о подозрительных логических выражениях. Например, когда вместо побитового «И» поставили логическое «И», или логическое выражение имеет одинаковые операнды:
-Werror
С этого, вообще говоря, стоило бы начать. Данный флаг делает все предупреждения ошибками. Код не скомпилируется при наличии хотя бы одного предупреждения.
Без этого флага всё остальное имеет мало смысла. Но если понять и принять мысль о том, что предупреждение — это что-то подозрительное, и их быть не должно, то именно этот флаг и позволит поддерживать код в чистоте.
Заключение
Резюмируя, для компилятора GCC (Clang кое-что из этого не умеет, к сожалению) я рекомендую включать следующий минимальный набор флагов, по необходимости дополняя его более сложными диагностиками.
Да, такой список флагов может породить большое количество ошибок, которые поначалу могут показаться излишними. Но явное лучше неявного. Если знаешь, что делаешь — делай. Но делай это так, чтобы всем было понятно, что именно так ты и хотел. Поработав таким образом хотя бы неделю, вы поймёте, насколько это прекрасно, и уже не сможете вернуться обратно.
Любите ваш компилятор и помогайте ему помогать вам писать программы.
Errors
Table of contents
The vast majority of error messages generated by GROMACS are descriptive, informing the user where the exact error lies. Some errors that arise are noted below, along with more details on what the issue is and how to solve it.
General
Cannot allocate memory
The executed script has attempted to assign memory to be used in the calculation, but is unable to due to insufficient memory.
Possible solutions are:
pdb2gmx
Residue ‘XXX’ not found in residue topology database
For new users, this error appears because they are running pdb2gmx blindly on a PDB file they have without consideration of the contents of the file. A force field is not something that is magical, it can only deal with molecules or residues (building blocks) that are provided in the residue database or included otherwise.
If there is not an entry for this residue in the database, then the options for obtaining the force field parameters are:
Once you have determined the parameters and topology for your residue, see adding a residue to a force field for instructions on how to proceed.
Long bonds and/or missing atoms
Chain identifier ‘X’ was used in two non-sequential blocks
This means that within the coordinate file fed to pdb2gmx, the X chain has been split, possibly by the incorrect insertion of one molecule within another. The solution is simple: move the inserted molecule to a location within the file so that it is not splitting another molecule.
This message may also mean that the same chain identifier has been used for two separate chains. In that case, rename the second chain to a unique identifier.
WARNING: atom X is missing in residue XXX Y in the pdb file
Atom X in residue YYY not found in rtp entry
No force fields found (files with name ‘forcefield.itp’ in subdirectories ending on ‘.ff’)
This means your environment is not configured to use GROMACS properly, because pdb2gmx cannot find its databases of forcefield information. This could happen because a GROMACS installation was moved from one location to another. Either follow the instructions about getting access to GROMACS after installation or re-install GROMACS before doing so.
grompp
Found a second defaults directive file
One solution is to simply comment out (or delete) the lines of code out in the file where it is included for the second time i.e.,
Invalid order for directive xxx
In particular, » Invalid order for directive defaults » is a result of defaults being set in the topology or force field files in the inappropriate location; the [defaults] section can only appear once and must be the first directive in the topology. The [defaults] directive is typically present in the force field file ( forcefield.itp ), and is added to the topology when you #include this file in the system topology.
If the directive in question is atomtypes (which is the most common source of this error) or any other bonded or nonbonded [*types] directive, typically the user is adding some non-standard species (ligand, solvent, etc) that introduces new atom types or parameters into the system. As indicated above, these new types and parameters must appear before any [moleculetype] directive. The force field has to be fully constructed before any molecules can be defined.
Atom index n in position_restraints out of bounds
WRONG:
RIGHT:
System has non-zero total charge
Notifies you that counter-ions may be required for the system to neutralize the charge or there may be problems with the topology.
If the charge is a non-integer, then this indicates that there is a problem with the topology. If pdb2gmx has been used, then look at the right hand comment column of the atom listing, which lists the cumulative charge. This should be an integer after every residue (and/or charge group where applicable). This will assist in finding the residue where things start departing from integer values. Also check the capping groups that have been used.
If the charge is already close to an integer, then the difference is caused by rounding errors and not a major problem.
Note for PME users: It is possible to use a uniform neutralizing background charge in PME to compensate for a system with a net background charge. There is probably nothing wrong with this in principle, because the uniform charge will not perturb the dynamics. Nevertheless, it is standard practice to actually add counter-ions to make the system net neutral.
Incorrect number of parameters
Look at the topology file for the system. You’ve not given enough parameters for one of the bonded definitions. Sometimes this also occurs if you’ve mangled the Include File Mechanism or the topology file format (see: GROMACS Manual Chapter 5) when you edited the file.
Number of coordinates in coordinate file does not match topology
The most common reason for this is simply that the user has failed to update the topology file after solvating or adding additional molecules to the system, or made a typographical error in the number of one of the molecules within the system. Ensure that the end of the topology file being used contains something like the following, that matches exactly with what is within the coordinate file being used, in terms of both numbers and order of the molecules:
In a case when grompp can’t find any any atoms in the topology file at all ( number of coordinates in coordinate file (conf.gro, 648) does not match topology (topol.top, 0) ) and that error is preceded by warnings like:
Fatal error: No such moleculetype XXX
T-Coupling group XXX has fewer than 10% of the atoms
The cut-off length is longer than half the shortest box vector or longer than the smallest box diagonal element. Increase the box size or decrease rlist
This error is generated in the cases as noted within the message. The dimensions of the box are such that an atom will interact with itself (when using periodic boundary conditions), thus violating the minimum image convention. Such an event is totally unrealistic and will introduce some serious artefacts. The solution is again what is noted within the message, either increase the size of the simulation box so that it is at an absolute minimum twice the cut-off length in all three dimensions (take care here if are using pressure coupling, as the box dimensions will change over time and if they decrease even slightly, you will still be violating the minimum image convention) or decrease the cut-off length (depending on the force field utilised, this may not be an option).
Unknown left-hand XXXX in parameter file
Atom index (1) in bonds out of bounds
This kind of error looks like
XXX non-matching atom names
This error usually indicates that the order of the topology file does not match that of the coordinate file. When running grompp, the program reads through the topology, mapping the supplied parameters to the atoms in the coordinate file. If there is a mismatch, this error is generated. To remedy the problem, make sure that the contents of your [ molecules ] directive matches the exact order of the atoms in the coordinate file.
This error warns that some combination of settings will result in poor energy conservation at the longest cutoff, which occurs when charge groups move in or out of neighborlist range. The error can have two sources:
A similar error («The sum of the two largest charge group radii (X) is larger than rlist») can arise under two circumstances:
Invalid line in coordinate file for atom X
mdrun
Stepsize too small, or no change in energy. Converged to machine precision, but not to the requested precision
Further minimization may be achieved by using a different energy minimization method or by making use of double precision-enabled GROMACS.
LINCS/SETTLE/SHAKE warnings
Sometimes, when running dynamics, mdrun may suddenly stop (perhaps after writing several pdb files) after a series of warnings about the constraint algorithms (e.g. LINCS, SETTLE or SHAKE) are written to the log file. These algorithms often used to constrain bond lengths and/or angles. When a system is blowing up (i.e. exploding due to diverging forces), the constraints are usually the first thing to fail. This doesn’t necessarily mean you need to troubleshoot the constraint algorithm. Usually it is a sign of something more fundamentally wrong (physically unrealistic) with your system. See also the advice here about diagnosing unstable systems.
1-4 interaction not within cut-off
Some of your atoms have moved so two atoms separated by three bonds are separated by more than the cut-off distance. This is BAD. Most importantly, do not increase your cut-off! This error actually indicates that the atoms have very large velocities, which usually means that (part of) your molecule(s) is (are) blowing up. If you are using LINCS for constraints, you probably also already got a number of LINCS warnings. When using SHAKE this will give rise to a SHAKE error, which halts your simulation before the «1-4 not within cutoff» error can appear.
There can be a number of reasons for the large velocities in your system. If it happens at the beginning of the simulation, your system might be not equilibrated well enough (e.g. it contains some bad contacts). Try a(nother) round of energy minimization to fix this. Otherwise you might have a very high temperature, and/or a timestep that is too large. Experiment with these parameters until the error stops occurring. If this doesn’t help, check the validity of the parameters in your topology!
Simulation running but no output
Not an error as such, but mdrun appears to be chewing up CPU time but nothing is being written to the output files. There are a number of reasons why this may occur:
Can not do Conjugate Gradients with constraints
Pressure scaling more than 1%
This error tends to be generated when the simulation box begins to oscillate (due to large pressures and / or small coupling constants), the system starts to resonate and then crashes. This can mean that the system isn’t equilibrated sufficiently before using pressure coupling. Therefore, better / more equilibration may fix the issue.
It is recommended to observe the system trajectory prior and during the crash. This may indicate if a particular part of the system / structure is the problem.
This error can also appear when using a timestep that is too large, e.g. 5 fs, in the absence of constraints and / or virtual sites.
Range Checking error
This usually means your simulation is blowing up. Probably you need to do better energy minimization and/or equilibration and/or topology design.
X particles communicated to PME node Y are more than a cell length out of the domain decomposition cell of their charge group
This is another way that mdrun tells you your system is blowing up. In GROMACS version 4.0, domain decomposition was introduced to divide the system into regions containing nearby atoms (for more details, see the manual or the GROMACS 4 paper). If you have particles that are flying across the system, you will get this fatal error. The message indicates that some piece of your system is tearing apart (hence out of the «cell of their charge group»). Refer to the Blowing Up page for advice on how to fix this issue.
A charge group moved too far between two domain decomposition steps.
As immediately above.
Software inconsistency error:
Some interactions seem to be assigned multiple times
As immediately above.